Algorithm to determine possible groups of items

后端 未结 6 1735
遥遥无期
遥遥无期 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:42

    A tree is the best way to think about it I think, but you can use recursion to build one without explicitly making a tree. You can think of the root as your total. Using groups of size 3-7, you need to find some combination of groups that sums up to your total.

    You can use 0 groups of 7, 1 group of 7, 2 groups of 7, etc. For each of those values, you can use 0 groups of 6, 1 group of 6, etc. The first level of your tree will represent how many 7's were used. The second level is how many 6's were used, etc. When you use x 7's, then you need to figure out how many combinations of 6's, 5's, 4's, and 3's you can use to sum up to (sum-x*7), and so on for each lower level (recursive call).

    Your tree will always have 5 levels.

    Using recursion to build the tree, here is a small Python code sample (with no attempt to prune the tree, it will explore the entire thing).

    MIN = 3
    MAX = 7
    
    def findComb(remaining, start, path):
       times = remaining/start
    
       if start == MIN:
           if remaining % MIN == 0:
               print "%s, %d %d's" % (path[1:], times, start)
           return
    
       for i in range(0, times+1):
           findComb(remaining- (i*start), start-1, "%s, %d %d's" % (path, i, start))
    
    
    findComb(12, MAX, "")
    

    This outputs:

    0 7's, 0 6's, 0 5's, 0 4's, 4 3's
    0 7's, 0 6's, 0 5's, 3 4's, 0 3's
    0 7's, 0 6's, 1 5's, 1 4's, 1 3's
    0 7's, 1 6's, 0 5's, 0 4's, 2 3's
    0 7's, 2 6's, 0 5's, 0 4's, 0 3's
    1 7's, 0 6's, 1 5's, 0 4's, 0 3's
    

提交回复
热议问题