0-1 背包问题题解 Java 语言
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = sc.nextInt();
int[] w = new int[n];
int[] v = new int[n];
for (int it = 0; it < n; it++) {
w[it] = sc.nextInt();
v[it] = sc.nextInt();
}
int W = sc.nextInt() + 1;
int[][] dp = new int[n][W];
for (int i = 1; i < n; i++) {
for (int j = 1; j < W; j++) {
if (j < w[i - 1]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i - 1]]
+ v[i - 1]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < W; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
System.out.println(dp[n - 1][W - 1]);
}
}