推出公式:
第三个就是:让上一次的和(新加入商品容量+(总空间-新加入的商品容量)也就是剩余空间的最大值,剩余空间的最大值去上一层找)
package Algorithm.dac.knapsack;public class KnapsackProblem {public static void main(String []args){int [] weight = {1, 4, 3};//物品的重量int [] value = {1500, 3000, 2000};//物品的价值int m = 4; //背包容量int n = value.length; //物品的个数//创建二维数组//v[i][j]表示在前i个物品中能够装入容量为j的背包中的最大价值int [] [] v = new int[n+1][m+1];int [] [] path = new int[n+1][m+1];//初始化第一行和第一列,这里可以不处理,默认就是0for (int i = 0; i < v.length; i++) {v[i][0] = 0; //第一列设置为 0}for (int i = 0; i < v[0].length; i++) {v[0][i] = 0;//将第一行设置为 0}//根据公式来动态规划处理for (int i = 1; i < v.length; i++) {for (int j = 1; j < v[0].length; j++) {if (weight[i -1] > j){v[i][j] = v[i-1][j];}else {//v[i][j] = Math.max(v[i-1][j], value[i-1] + v[i-1][j-weight[i-1]]);if (v[i-1][j] < value[i-1] + v[i-1][j-weight[i-1]]){v[i][j] = value[i-1] + v[i-1][j-weight[i-1]];path[i][j] = 1;}else {v[i][j] = v[i-1][j];}}}}//输出一下vfor (int i = 0; i < v.length; i++) {for (int j = 0; j < v[0].length; j++) {System.out.print(v[i][j]+" ");}System.out.println();}System.out.println("===========");int i = path.length - 1;int j = path[0].length - 1;//v[i][j] = value[i-1] + v[i-1][j-weight[i-1]];//如果是1那么,v[i][j] = value[i-1] + v[i-1][j-weight[i-1]]; 就是 物品value[i-1] + v[i-1][j-weight[i-1]],在判断v[i-1][j-weight[i-1]]是1还是0,是1继续循环,是0就退出。while (i > 0 && j > 0){if (path[i][j] == 1) {System.out.println("物品:" + i + "加入背包");j = j - weight[i - 1];}i = i - 1;}}
}