● 完全背包
主要是看清01背包和完全背包的区别
//01背包 for(int i = 0;i<weight.size();i++){ for(int j = bagWeight;j>=weight[i];j--){ dp[j] = Math.max(dp[j],dp[j-weight[i]]+value[i]); } } //完全背包 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]); } }
● 518. 零钱兑换 II
//完全背包经典题目 class Solution { public int change(int amount, int[] coins) { int[] dp = new int[amount+1]; dp[0] = 1; for(int i = 0;i<coins.length;i++){ for(int j =coins[i];j<=amount;j++){ dp[j] += dp[j-coins[i]];//可以不断重复 } } return dp[amount]; } }
● 377. 组合总和 Ⅳ
class Solution { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target+1]; dp[0] = 1; for(int i = 0;i<=target;i++){ for(int j = 0;j<nums.length;j++){ if(i>=nums[j]){ dp[i] += dp[i-nums[j]]; } } } return dp[target]; } }