[英]Is there a way to recursively find the different ways a set of numbers can add up to a certain number?
I want to be able to find all the different ways a set of numbers(x) can be summed into a certain value, y but I'm having trouble even getting the base case right.我希望能够找到可以将一组数字(x)相加为某个值的所有不同方式,但是我什至无法正确设置基本情况。
For example:例如:
If I have x = set (1,2,3,4,5) and I want to see how many different ways y = 5 can be summed up using numbers from x:如果我有 x = set (1,2,3,4,5) 并且我想看看 y = 5 可以使用 x 中的数字求和有多少种不同的方式:
my recursive function would return 7 because:我的递归 function 将返回 7 因为:
'''
5
4+1
3+2
3+1+1
2+2+1
2+1+1+1
1+1+1+1+1
'''
def recur(x,y):
if y == x:
v += 1
if y > x:
v += 0
else:
#call recursively
This does not use recursion, but itertools.combinations_with_replacement
:这不使用递归,但
itertools.combinations_with_replacement
:
def all_combs(y, x=range(1, 5+1)):
all_combs = []
for i in range(1, y+1):
combs = combinations_with_replacement(x, i)
all_combs.extend([comb for comb in combs if sum(comb) == y])
return all_combs
combs = all_combs(5)
# [(5,), (1, 4), (2, 3), (1, 1, 3), (1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1)]
num_combs = len(combs) # 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.