01背包问题(二维dp)
题目讲解
public static void testWeightBagProblem(int[] weight, int[] value, int bagSize) {
int[][] dp = new int[weight.length][bagSize + 1];
for (int j = weight[0]; j <= bagSize; j++) {
dp[0][j] = value[0];
}
for (int i = 1; i < weight.length; i++) {
for (int j = 1; j <= bagSize; j++) {
if (j < weight[i]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
}
}
}
for (int[] arr : dp) {
System.out.println(Arrays.toString(arr));
}
}
01背包问题(一维dp)
题目讲解
public static void testWeightBagProblem(int[] weight, int[] value, int bagSize) {
int[] dp = new int[bagSize + 1];
dp[0] = 0;
for (int i = 0; i < weight.length; i++) {
for (int j = bagSize; j >= weight[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
}
}
System.out.println(Arrays.toString(dp));
}
416. 分割等和子集 (01背包问题应用)
题目讲解
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int n : nums) sum += n;
if (sum % 2 != 0) return false;
int target = sum / 2;
int[] dp = new int[target + 1];
for (int i = 0; i < nums.length; i++) {
for (int j = target; j >= nums[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
}
}
if(dp[target] == target) return true;
return false;
}
}