You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
Example 1:
coins = [1, 2, 5]
, amount = 11
return 3
(11 = 5 + 5 + 1)
Example 2:
coins = [2]
, amount = 3
return -1
.
这个题的最原始版本是问有多少种组合方式,暴力解法的话,一共是2^n种组合方式,同时没有具体问怎么组合,因此可以推测应该使用递归。dp的状态是最小值,更新公式如下所示,同时注意不能初始化为MAX_VALUE,否则溢出变为负数
class Solution {
public int coinChange(int[] coins, int amount) {
int[] res = new int[amount + 1];
for (int i = 1; i <= amount; i++) {
res[i] = Integer.MAX_VALUE - 1;
}
res[0] = 0;
for(int i = 0; i < coins.length; i++) {
for (int j = 0; j <= amount; j++) {
if(j >= coins[i]) {
res[j] = Math.min(res[j], res[j - coins[i]] + 1);
}
}
}
if(res[amount] == Integer.MAX_VALUE - 1){
return -1;
}
return res[amount];
}
}