You is given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins so need to make up that amount. If that amount of cannot is made up by any combination of the coins, return-1.
Example 1:
coins = [1, 2, 5], amount = one
return 3 (one = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return-1.
Note: You may assume so you have a infinite number of each
kind of coin.
Ideas
Given a number of coins of different value, assuming that the number of each coin is infinite, given a specific value, it is necessary to ask whether the value can be obtained with these combinations of coins, if the number of coins with the fewest use can be given.
Using dynamic programming, from 1 to the given value, amount the minimum number of coins that can be used to get that value. Source Code
class Solution {public:int Coinchange (vector<int>& coins, int amount) {
int a[10000];
int i,j,t;
for (i = 1;i <= amount;i + +) A[i] =-1;
A[0] = 0; for (i = 1;i <= amount;i + +) {for (j = 0;j < Coins.size (); j + +) {if ((i-coins[j))
= 0 && a[i-coins[j]] >= 0) {t = A[i-coins[j]] + 1;
if (a[i] = =-1 | | a[i] > t) a[i] = t;
}}} return A[amount]; }
};