def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print "sum(%s)=%s" % (partial, target)
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
上面的代码应该检查从列表中获得某个目标总和的次数。
如何修改它以使用递归来检查列表中任何数字组合的总和相等的次数?例如,[1,2,3]应该给出2的输出,因为1 + 2 = 3和3 = 2 + 1而[1,1,2,3,5]应该给出4。
答案 0 :(得分:0)
这样的事情应该有效:
def subset_sum(target, remaining, partial=()):
remaining = tuple(remaining)
if remaining == ():
return 1 if sum(partial) == target else 0
else:
return (subset_sum(target, partial, remaining[1:]) +
subset_sum(target, partial + remaining[:1], remaining[1:]))
>>> subset_sum(5, [1,1,2,3,5])
3
>>> subset_sum(2, [1,1,2,3,5])
2
我们在这里使用元组,我们不必担心对同一列表的多个引用相互干扰。元组是不可改变的,所以任何修改"不会泄漏到其他情况。