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
每種硬幣的數量是無限的——完全揹包問題
public int coinChange(int[] coins, int amount) {
//dp[i]表示金額爲i需要最少的硬幣數
int[] dp = new int[amount + 1];
//處理:沒有任何一種硬幣組合能組成總金額,返回 -1 的情況
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for(int i = 1; i <= amount; i ++) {
for(int j = 0; j < coins.length; j ++) {
if(coins[j] <= i) {
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
}
}
}
//如果沒有任何一種硬幣組合能組成總金額,返回 -1。
return dp[amount] > amount? -1 : dp[amount];
}