執行結果:
通過
顯示詳情
執行用時 :13 ms, 在所有 Java 提交中擊敗了68.96% 的用戶
內存消耗 :35.9 MB, 在所有 Java 提交中擊敗了51.50%的用戶
題目:
給定不同面額的硬幣 coins 和一個總金額 amount。編寫一個函數來計算可以湊成總金額所需的最少的硬幣個數。如果沒有任何一種硬幣組合能組成總金額,返回 -1。
示例 1:
輸入: coins = [1, 2, 5], amount = 11
輸出: 3
解釋: 11 = 5 + 5 + 1
示例 2:
輸入: coins = [2], amount = 3
輸出: -1
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/coin-change
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
動態規劃,這道題和完全平方很像。https://blog.csdn.net/qq_41901915/article/details/104232810
這道題的難點在於不存在的時候如何處理,如果不存在的時候,就會一直往前追溯,一直往前減去,一直到負數。如果存在的話,就會一直減去,直到0
代碼:
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp=new int[amount+1];
//讓所有項都是amount+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(i-coins[j]>=0)
{
dp[i]=Math.min(dp[i],dp[i-coins[j]]+1);
}
}
}
return dp[amount]>amount?-1:dp[amount];
}
}