LeetCode322零钱兑换
原题
完全背包
当优化后 容量应该从小到大遍历
因为当完全背包时,其物品时可以多次添加的
eg:
// 先遍历物品,再遍历背包
for(int i = 0; i < weight.size(); i++) { // 遍历物品
for(int j = weight[i]; j < bagWeight ; j++) { // 遍历背包容量
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
而当01背包时,其物品只能添加一次
故只能从大到小遍历
eg:
for(int i = 0; i < weight.size(); i++) { // 遍历物品
for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
题解
class Solution {
public int coinChange(int[] coins, int amount) {
int max = amount + 1;
int[] dp = new int[amount+1];
Arrays.fill(dp,max);
dp[0] = 0;
for(int i=0;i<coins.length;i++){
for(int j=1;j<=amount;j++){
if(coins[i]<=j){
dp[j] = Math.min(dp[j],dp[j-coins[i]]+1);
}
}
}
if(dp[amount]==max){
//先初始化DP table各个元素为amount + 1(代表不可能存在的情况),在遍历时如果金额凑不出则不更新,于是若最后结果仍然是amount + 1,则表示金额凑不出
return -1;
}else{
return dp[amount];
}
}
}

浙公网安备 33010602011771号