问题描述
给定一个排序的连续整数数组,从 1 到 X 找到总和为 N 的 K 个数字的所有组合?知道数字不能重复 例如:
array = [1,2,3,4,5]
K =3
N= 8
Output:
1 2 5
1 3 4
有什么建议吗?
解决方法
您可以使用 python 的 combinations
模块中的 itertools
函数。
>>> from itertools import combinations
>>> array=[1,2,3,4,5]
>>> K=3
>>> N=8
>>> for comb in combinations(array,K):
... if sum(comb) == N:
... print(' '.join(list(map(str,comb))))
...
1 2 5
1 3 4