题目描述:
标签:动态规划
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
代码:
思路分析:动态规划五部曲(完全背包问题)
1、确定dp数组以及下标的含义——这里dp[i]是指背包重量是i,凑成该重量的最少硬币数
2、确定递推公式,典型背包公式递推,dp[j] = min(dp[j-coins[i]]+1,dp[j])
3、dp数组初始化,dp[0]=0,记得dp初始化需要填充Integer.MAX_VALUE,使用Arrays.fill(a,1)
4、确定遍历顺序,双层for循环遍历,i从0到coins.length(遍历所有硬币),j从当前硬币重量coins[i]到需要的总重量amount
5、举例推导dp数组
6、最后返回dp[amount],先判断是否dp[amount]==Integer.MAX_VALUE,如果是则返回-1,其他返回dp[amount]
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount+1];
Arrays.fill(dp,Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 0;i < coins.length;i++){
for(int j = coins[i];j <= amount;j++){
if(dp[j-coins[i]] != Integer.MAX_VALUE){
dp[j] = Math.min(dp[j-coins[i]]+1,dp[j]);
}
}
}
if(dp[amount] == Integer.MAX_VALUE) return -1;
return dp[amount];
}
}