简体   繁体   English

有没有办法递归地找到一组数字可以加起来为某个数字的不同方式?

[英]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.

相关问题 如何找到整数1,2,3可以累加n的方式? - How to find number of ways that the integers 1,2,3 can add up to n? 如何获得一个 ndarray,其中包含将 N 个元素加起来的不同方法? - How can I get a ndarray which contains the different ways of adding up to N a certain number of elements? 如何生成一定数量的随机整数,它们加起来等于一定数量并且至少是一定数量或更多? - How to generate a certain number of random whole numbers that add up to a certain number and are at least a certain number or more? 相关概率找出掷两个骰子时加起来达到一定数量的不同掷骰组合 - Dependent probabilities find out the different combinations of rolls that add up to a certain number when rolling two dice 如何找到总和为某个数字的所有数字组合? - How to find all combinations of numbers summing up to a certain number? 查找总和为特定数字的数字列表的算法 - Algorithm to find a list of numbers that sum up to a certain number 在正数列表中找到相加为X的所有元素 - find all elements in a list of positive numbers that add up to number X 查找整数列表中添加到数字的所有数字 - Find all numbers in a integer list that add up to a number 从列表中查找三个数字相加为特定数字 - Find three numbers from a list that add up to a specific number 从列表中找出两个相加为特定数字的数字 - Find two numbers from a list that add up to a specific number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM