01背包问题 二维
视频讲解:带你学透0-1背包问题!| 关于背包问题,你不清楚的地方,这里都讲了!| 动态规划经典问题 | 数据结构与算法_哔哩哔哩_bilibili
import java.util.Arrays;
public class BagProblem {
public static void main(String[] args) {
int[] weights = {1, 3, 4};
int[] values = {15, 20, 30};
int capacity = 4;
solveKnapsackProblem(weights, values, capacity);
}
public static void solveKnapsackProblem(int[] weights, int[] values, int capacity) {
int numberOfItems = weights.length;
int[][] dp = new int[numberOfItems + 1][capacity + 1];
for (int i = 1; i <= numberOfItems; i++) {
for (int j = 1; j <= capacity; j++) {
if (j < weights[i - 1]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1]);
}
}
}
System.out.println(Arrays.toString(dp[numberOfItems]));
}
}
01背包问题 一维
视频讲解:带你学透01背包问题(滚动数组篇) | 从此对背包问题不再迷茫!_哔哩哔哩_bilibili
public static void main(String[] args) {
int[] weights = {1, 3, 4};
int[] values = {15, 20, 30};
int capacity = 4;
findMaxValue(weights, values, capacity);
}
public static void findMaxValue(int[] weights, int[] values, int capacity) {
int[] maxValues = new int[capacity + 1];
int numberOfItems = weights.length;
for (int i = 0; i < numberOfItems; i++) {
for (int j = capacity; j >= weights[i]; j--) {
maxValues[j] = Math.max(maxValues[j], maxValues[j - weights[i]] + values[i]);
}
}
for (int j = 0; j <= capacity; j++) {
System.out.print(maxValues[j] + " ");
}
}
416. 分割等和子集
本题是 01背包的应用类题目
视频讲解:动态规划之背包问题,这个包能装满吗?| LeetCode:416.分割等和子集_哔哩哔哩_bilibili
public class Solution {
public static void main(String[] args) {
int[] numbers = {1, 5, 11, 5};
boolean canEqualPartition = canPartition(numbers);
System.out.println("Can partition: " + canEqualPartition);
}
public static boolean canPartition(int[] numbers) {
int length = numbers.length;
int totalSum = 0;
for (int number : numbers) {
totalSum += number;
}
if (totalSum % 2 != 0) {
return false;
}
int halfSum = totalSum / 2;
boolean[][] dp = new boolean[length][halfSum + 1];
if (numbers[0] <= halfSum) {
dp[0][numbers[0]] = true;
}
for (int i = 1; i < length; i++) {
for (int capacity = 0; capacity <= halfSum; capacity++) {
dp[i][capacity] = dp[i - 1][capacity];
if (numbers[i] == capacity) {
dp[i][capacity] = true;
} else if (numbers[i] < capacity) {
dp[i][capacity] = dp[i - 1][capacity] || dp[i - 1][capacity - numbers[i]];
}
}
}
return dp[length - 1][halfSum];
}
}