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
.
Note:
You may assume that you have an infinite number of each kind of coin.
这道题的动规的思路比较好想,但是对于一些边界条件考虑的不是很周全。在进行状态转移方程中: dp[i+coins[j]] = Math.min( dp[i+coins[j]], dp[i] + 1); 能够进行二者比较的前提有三个:1. i + coins[j] <= amount 2. i+coins[j]>=0, 这个条件感觉有点费解,是因为越界?? 因为有看到测试用例用integer.max_value作为coin的。 3. 如果当前dp[i] 的值是正无穷,那么不能够用它进行状态转移。因为比较是没有意义的,这个位置目前还没有计算出最优解,那么它就不能作用于它后面(i + coint[j]的特定的几个位置)的那些元素。
有空会跟同学讨论下,这些边界条件都是怎么考虑到的。
代码:
public int coinChange(int[] coins, int amount) {
if(coins == null || coins.length == 0) return -1;
if(amount == 0) return 0;
if(coins.length == 1){
if(amount % coins[0] != 0){
return -1;
}
return amount/coins[0];
}
int[] dp = new int[amount+1];
for(int i=1;i<=amount;i++){
dp[i] = Integer.MAX_VALUE;
}
dp[0] = 0;
for(int i=0;i<=amount;i++){
for(int j=0;j<coins.length;j++){
if(i+coins[j]<=amount && i+coins[j]>=0 && dp[i]!= Integer.MAX_VALUE)
dp[i+coins[j]] = Math.min( dp[i+coins[j]], dp[i] + 1);
}
}
return dp[dp.length-1] == Integer.MAX_VALUE?-1:dp[dp.length-1];
}