这是一些蟒蛇:
def sumperms(n, total = None):
if total == None:
# total is the target sum, if not specified, set to 2n
total = 2 * n
if n == 1:
# if n is 1, then there is only a single permutation
# return as a tuple.
# python's syntax for single element tuple is (element,)
yield (total,)
return
# iterate i over 0 ... total
for i in range(total + 1):
# recursively call self to solve the subproblem
for perm in sumperms(n - 1, total - i):
# append the single element tuple to the "sub-permutation"
yield (i,) + perm
# run example for n = 3
for perm in sumperms(3):
print perm
输出:
(0, 0, 6)
(0, 1, 5)
(0, 2, 4)
(0, 3, 3)
(0, 4, 2)
(0, 5, 1)
(0, 6, 0)
(1, 0, 5)
(1, 1, 4)
(1, 2, 3)
(1, 3, 2)
(1, 4, 1)
(1, 5, 0)
(2, 0, 4)
(2, 1, 3)
(2, 2, 2)
(2, 3, 1)
(2, 4, 0)
(3, 0, 3)
(3, 1, 2)
(3, 2, 1)
(3, 3, 0)
(4, 0, 2)
(4, 1, 1)
(4, 2, 0)
(5, 0, 1)
(5, 1, 0)
(6, 0, 0)