繁体   English   中英

给定一个整数数组,从 1 到 X 找到总和为 N 的 K 个数字

[英]Given an array of integers, from 1 to X find K numbers that sum to N

给定一个排序的连续整数数组,从 1 到 X 找到所有和为 N 的 K 个数的组合? 知道数字不能重复 例如:

array = [1,2,3,4,5]
K =3
N= 8
Output: 
1 2 5
1 3 4

有小费吗?

您可以使用 python 的itertools模块中的 function combinations

>>> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM