Title: Given coins of different denominations of coins and a total amount of amount. We can write a function to calculate the minimum number of coins needed to make up the total amount. If there is no combination can be composed of any of a total amount of coins, return -1.
def coins_change(coins,amount): dp = [amount+1]*(amount+1) dp[0] = 0 for i in range(1,amount+1): for j in range(len(coins)): if i>=coins[j]: dp[i] = min(dp[i],dp[i-coins[j]]+1) return -1 if dp[-1]>amount else dp[-1] coins = [1,2,5] amount = 11 print(coins_change(coins,amount))
Note:
Knapsack problem, the first sub-problems minimum number of coins per weight. dp is the minimum number of coins stored in the weight index. dp [i] = min (dp [i], dp [i-coins [j]] + 1) and is not placed into the current coin, minimum.