简体   繁体   中英

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). It should return the number of combinations from the list that sums to k, the order doesn't matter(The coin change problem). 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.

It should return 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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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