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:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
给出一个amount,给出几种coin,无限枚数,问最少能用几枚硬币组成amount
思路:
dp
倒推,用组成(amount-当前coin)的硬币枚数+(当前coin)1枚
即dp[amount - coin] + 1
遍历所有硬币,比如amount= 11
第一行表示coin=1参与的时候最少的硬币数,第二行表示在coin=2可以参与(也可以不参与,只有1)的情况下最少的枚数。同理coin=5。
amount: 0 1 2 3 4 5 6 7 8 9 10 11
1 0 1 2 3 4 5 6 7 8 9 10 11
2 0
5
(coin)
coin是2,amount=1的时候,amount-coin<0,所以对于小于coin本身的amount,直接跳过,保留上次的结果。
到amount=2,dp[2][amount - coin]+1 = dp[2][0] + 1,即用一枚2硬币本身就能构成amount=2
取min(dp[1][amount], dp[2][amount - coin] + 1)
进一步压缩dp数组到一维,即在上一枚硬币的基础上更新
*注意硬币无法组成amount时是∞,因此在∞的时候返回-1
*硬币无法组成amount,即dp[i - coin] = ∞时,不需要更新dp,继续保持无法组成的状态
//7ms
public int coinChange(int[] coins, int amount) {
if (coins == null || coins.length == 0 || amount < 0) {
return -1;
}
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
if (dp[i - coin] != Integer.MAX_VALUE) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
if (dp[amount] == Integer.MAX_VALUE) {
return -1;
}
return dp[amount];
}