The minimum number of coins the sum of which is S

后端 未结 12 1354
我寻月下人不归
我寻月下人不归 2020-11-30 05:06

Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type a

12条回答
  •  暖寄归人
    2020-11-30 05:37

    As already pointed out, Dynamic Programming suits best for this problem. I have written a Python program for this:-

    def sumtototal(total, coins_list):
        s = [0]
        for i in range(1, total+1):
            s.append(-1)
            for coin_val in coins_list:
                if i-coin_val >=0 and s[i-coin_val] != -1 and (s[i] > s[i-coin_val] or s[i] == -1):
                    s[i] = 1 + s[i-coin_val]
    
        print s
        return s[total]
    
    total = input()
    coins_list = map(int, raw_input().split(' '))
    print sumtototal(total, coins_list)
    

    For input:

    12 2 3 5

    The output would be:

    [0, -1, 1, 1, 2, 1, 2, 2, 2, 3, 2, 3, 3] 3 The list_index is the total needed and the value at list_index is the no. of coins needed to get that total. The answer for above input(getting a value 12) is 3 ( coins of values 5, 5, 2).

提交回复
热议问题