题目
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回
-1
。
分析
用动态规划,自底向上的计算1,2,3,45,……amount的最小硬币个数。
dp[i] = min(dp[i] , dp[i-coins[j]]+1)
代码
class Solution {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
int[] dp = new int[amount + 1];
for (int i = 1; i <= amount; i++) {
dp[i] = Integer.MAX_VALUE;
for(int c : coins){
if (i >= c && dp[i-c] != Integer.MAX_VALUE){
dp[i] = Math.min(dp[i], dp[i-c]+1);
}
}
}
if (dp[amount]<Integer.MAX_VALUE && dp[amount] > 0)return dp[amount];
else return -1;
}
}