繁体   English   中英

如何找到总和为某个数字的所有数字组合?

[英]How to find all combinations of numbers summing up to a certain number?

给出一个总和,例如 25,并给出数字,例如 2、5、10 您需要找到所有组合来选择这个数量。 即程序应为 output 5 + 5 + 5 + 5 + 5、5 + 5 + 5 + 10、5 + 10 + 10、2 + 2 + 2 + 2 + 2 + 10 + 5 等等。

您推荐使用哪些算法/方法/库?

您可以使用itertools获取所有组合,然后只保留总和为 25 的组合。我使用with_replacement是因为相同的值可以出现两次。 此外,我使用了地板部门,因为没有一个数字比最小的数字更频繁。

from itertools import combinations_with_replacement

candidates = list()

for i in range(25//2):  # floor division of largest by smallest
    candidates.extend(list(combinations_with_replacement([2, 5, 10], i)))

positive_cases = [i for i in candidates if sum(i) == 25]
[(5, 10, 10), (5, 5, 5, 10), 
 (5, 5, 5, 5, 5), (2, 2, 2, 2, 2, 5, 10), 
 (2, 2, 2, 2, 2, 5, 5, 5), 
 (2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5)]

数字是1/((1-x^2)(1-x^5)(1-x^10))中x^25的系数

所以,同情是你的朋友。

您也可以使用动态编程来做到这一点。

暂无
暂无

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

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