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
.
Tips:给定一个coins[]数组,表示现有的硬币类型;给定一个整数amount表示要组成的金钱总数。
根据coins[],求出组成amount所需的最少的硬币数。
解法一:循环 :①初始化一个数组dp,并将数组中的值都赋值为Integer.MAX_VALUE;
② 两层循环,第一层遍历amount 第二层遍历coins[].length,当总钱数减去一个硬币的值小于0,证明无法组成该钱数,continue。或者上一步的dp值仍为初始值Integer.MAX_VALUE,也应continue;
都满足条件时,dp选择当前dp值与上一步dp值加一后的最小值,dp[i]=Math.min(dp[i],1+dp[i-coins[j]] );。
③如果无法组成amount这个钱数,就返回-1,否则返回dp[amount].
public int coinChange(int[] coins, int amount) { int[] dp= new int[amount+1]; for(int i=0;i<=amount;i++){ dp[i]=Integer.MAX_VALUE; } dp[0]=0; for(int i=1;i<=amount;i++){ for(int j=0;j<coins.length;j++){ if(i-coins[j]<0 ||dp[i-coins[j]]==Integer.MAX_VALUE) continue; dp[i]=Math.min(dp[i],1+dp[i-coins[j]] ); } } return dp[amount]==Integer.MAX_VALUE?-1:dp[amount]; }
解法二: 递归 :当前组成amount所需的硬币数,与上一步有关.假设我们已经找到了能组成amount的最少硬币数,那么最后一步,我们可以选择任意的一个硬币,加入这个硬币之前,组成的金钱数为r,这时,r = amount-coins[i](需要循环所有的coins)。依次向前推,直到r等于0
或者小于0.
public int coinChange(int[] coins, int amount) {
if (amount < 0)
return 0;
return coinChangeCore(coins, amount, new int[amount]);
}
private int coinChangeCore(int[] coins, int amount, int[] count) {
if (amount < 0)
return -1;
if (amount == 0)
return 0;
//剪枝
if (count[amount - 1] != 0)
return count[amount - 1];
int min = Integer.MAX_VALUE;
for (int i = 0; i < coins.length; i++) {
int ans = coinChangeCore(coins, amount - coins[i], count);
if (ans >= 0 && ans < min) {
min = 1 + ans;
}
}
count[amount - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
return count[amount - 1];
}