有N件物品和一个容量为V的背包,第i件物品消耗的容量为Ci,价值为Wi,求解放入哪些物品可以使得背包中总价值最大。
解法一:
static int[] w = new int[]{0, 2, 3, 5, 5}; static int[] v = new int[]{0, 2, 4, 3, 7}; public static int test2(int i , int c){ int result = 0; if(i == 0 || c == 0){ return 0; }else if(w[i] > c){ result = test2(i-1,c); }else { int temp1 = test2(i - 1, c); int temp2 = test2(i-1,c-w[i])+v[i]; result = Math.max(temp1,temp2); } return result; }
解法二:
static int[] w = new int[]{0, 2, 3, 5, 5}; static int[] v = new int[]{0, 2, 4, 3, 7}; static int[][] result = new int[5][11];public static int test3(int i , int c){ // 初始化 for(int n =0; n <= i; n++){ result[n][0]=0; } for(int n = 0 ; n <= c; n++){ result[0][n]=0; } for(int n = 1; n <= i; n ++){ for (int m = 1; m <= c; m++) { if(m < w[n]){ result[n][m] = result[n-1][m]; }else { if(result[n-1][m]>result[n-1][m-w[n]]+v[n]){ result[n][m] = result[n-1][m]; }else { result[n][m] = result[n-1][m-w[n]]+v[n]; } } } } return result[i][c]; }
参考文档:
https://www.cnblogs.com/mfrank/p/10849505.html
https://zhuanlan.zhihu.com/p/93857890