简体   繁体   English

如何只计算一次硬币变化组合?

[英]How to count the coin change combinations only once?

I have an assignment to make a function that receives only an integer and a list of integers(can't add anything else).我有一个任务是制作一个 function ,它只接收一个 integer 和一个整数列表(不能添加任何其他内容)。 It should return the number of combinations from the list that sums to k, the order doesn't matter(The coin change problem).它应该从列表中返回总和为 k 的组合数,顺序无关紧要(硬币找零问题)。 Also, I need to use recursion.另外,我需要使用递归。 Here's what I did:这是我所做的:

def coin(k, lst):
    if k == 0:
        return 1
    if k < 0:
        return 0
    else:
        sum = 0
        for i in range(len(lst)):
            sum += coin(k - lst[i], lst)
        return sum

The problem is it sums same combination multiple times.问题是它多次对相同的组合求和。 For example,例如,

coin(5, [1, 2, 5, 6])

returns 9.返回 9。

It should return 4 (11111, 122, 1112, 5).它应该返回 4(11111、122、1112、5)。

Your code is actually missing required parameters, also you are using a for loop with recursion that's what messing up with the essence of recursion.您的代码实际上缺少必需的参数,而且您正在使用带有递归的 for 循环,这弄乱了递归的本质。 Try using this code:尝试使用此代码:

def coin(k, lst, n):
    if(k == 0):
        return 1
    elif(n==0 or k<0):
        return 0
    else:
        return coin(k, lst, n-1) + coin(k-lst[n-1], lst, n)
arr = [1, 2, 5, 6]
n = len(arr)
print(coin(5, arr, n))

In the else part: The first recursive call is leaving the current array element behind and calling the remaining array.在 else 部分:第一个递归调用是留下当前数组元素并调用剩余的数组。 The Second recursive call is subtracting the current array element from the required change(k) and recalling again with the current element so as to choose it again in future calls.第二次递归调用是从所需的 change(k) 中减去当前数组元素,然后用当前元素再次调用,以便在以后的调用中再次选择它。

Also, the addition between the first and second call indicates that we want all the possible combinations, that can either be derived from first recursive call or second recursive call此外,第一次和第二次调用之间的相加表明我们想要所有可能的组合,可以从第一次递归调用或第二次递归调用中派生

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

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