public class Main {
public static void main(String[] args) {
int[] w = {1,4,3};
int[] val = {1500,3000,2000};
int n = 4;
int[][] dp = new int[w.length+1][n+1];
for (int i = 0; i < n+1; i++) {
dp[0][i] = 0;
}
for (int i = 0; i < w.length+1; i++) {
dp[i][0] = 0;
}
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
System.out.print(dp[i][j]+" ");
}
System.out.println();
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[i].length; j++) {
if (w[i-1] > j) {
dp[i][j] = dp[i-1][j];
} else {
dp[i][j] = Math.max(dp[i-1][j],val[i-1]+dp[i-1][j-w[i-1]]);
}
}
}
System.out.println();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
System.out.print(dp[i][j]+" ");
}
System.out.println();
}
System.out.println(dp[dp.length-1][dp[0].length-1]);
}
}
如何拿到最大价值组合的商品:
int[][] path = new int[w.length+1][n+1];
if (dp[i-1][j] < val[i-1]+dp[i-1][j-w[i-1]) {
dp[i][j] = val[i-1]+dp[i-1][j-w[i-1];
path[i][j] = 1;
} else {
dp[i][j] = dp[i-1][j];
int i = path.length-1;
int j = path[0].length-1;
while (i >= 0 && j >= 0) {
if (path[i][j] == 1) {
System.out.printf("第%d个商品放入背包\n",i);
j -= w[i-1];
}
i--;
}
|