这里写自定义目录标题
将列表NUM中的数字求和,哪些数字相加等于23,请列出?
下面这段代码很有趣也很简洁。只用python本身,不使用任何插件包。
num = [1,2,3,10,4,5,6,8,12,11]
def count(num, n):
combinations_impl(num, n, [])
def combinations_impl(num, n, ls):
if n == 0:
print(ls)
return
for i in range(0, len(num)):
if num[i] <= n:
ls.append(num[i])
combinations_impl(num[i + 1:], n - num[i], ls)
ls.pop()
else:
break
count(num, 23)
运行结果:
[1, 2, 3, 4, 5, 8]
[1, 2, 3, 5, 12]
[1, 2, 10, 4, 6]
[1, 2, 8, 12]
[1, 3, 10, 4, 5]
[1, 3, 5, 6, 8]
[1, 10, 4, 8]
[1, 10, 12]
[1, 4, 6, 12]
[2, 3, 10, 8]
[2, 3, 4, 6, 8]
[2, 3, 6, 12]
[2, 10, 5, 6]
[2, 4, 5, 12]
[3, 10, 4, 6]
[3, 8, 12]
[10, 5, 8]
[4, 5, 6, 8]
[5, 6, 12]
[12, 11]