排列组合,为了避免重复,就如题中举例,划分数有大到小排列,比如6=5+1,这样1+5就不行
递归:从6里取2作为第一个的话,剩余4再划分时,不能超过2,这样就不会出现3,2,1,然后2,3,1再来一遍的情况:def fulldivision(n,limit,state):
if n==1 or n == 0:
yield (n,)
else:
for i in range(min(n,limit),0,-1):
for result in fulldivision(n-i,i,state + (i,)):
yield (i,) + result
c = 0
for res in fulldivision(6,6,()):
c += 1
print ('Solution %d: ' % c,res)
结果如下:Solution 1: (6, 0)
Solution 2: (5, 1)
Solution 3: (4, 2, 0)
Solution 4: (4, 1, 1)
Solution 5: (3, 3, 0)
Solution 6: (3, 2, 1)
Solution 7: (3, 1, 1, 1)
Solution 8: (2, 2, 2, 0)
Solution 9: (2, 2, 1, 1)
Solution 10: (2, 1, 1, 1, 1)
Solution 11: (1, 1, 1, 1, 1, 1)
|