Algorithm to determine possible groups of items

后端 未结 6 1804
遥遥无期
遥遥无期 2021-02-03 11:51

I am scratching my head trying to do this and it\'s eating me up. I know it is not THAT complex. I have a number of items, this number can be equal or greater than three. Then I

6条回答
  •  耶瑟儿~
    2021-02-03 12:45

    It can be done with recursion. You don't say if you just want the number of possibilities or the actual possibilities.

    One thing you want to do is avoid repetition meaning don't count 4 and 3 also as 3 and 4. One way to do that is to create sequences of non-descending group sizes.

    Probably the best data structure for this is a tree:

    root
    +- 12
    +- 9
    |  +- 3
    +- 8
    |  +- 4
    +- 7
    |  +- 5
    +- 6
    |  +- 6
    |  +- 3
    |     +- 3
    +- 5
    |  +- 4
    |     +- 3
    +- 4
    |  +- 4
    |     +- 4
    +- 3
       +- 3
          +- 3
             +- 3
    

    Then to find the number of combinations you simply count the leaf nodes. To find the actual combinations you just walk the tree.

    The algorithm for building such a tree goes something like this:

    • Function buildTree(int size, int minSize, Tree root)
    • Count i from size down to minSize;
    • Create a child of the current node with value i;
    • For each j from minSize to i that is less than or equal to i
      • Create a new child of value j
      • Call `buildTree(j, minSize, new node)

    or something very close to that.

提交回复
热议问题