标签:
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
If we have 4
items with size [2, 3, 5, 7]
, the backpack size is 11, we can select [2, 3, 5]
, so that the max size we can fill this backpack is 10
. If the backpack size is 12
. we can select[2, 3, 7]
so that we can fulfill the backpack.
You function should return the max size we can fill in the given backpack.
分析:
看似这题是NP-hard问题,但是实际上可以用DP解决。result[i][j] 表示选取数组A中前i个数并且backpack size 是 j的时候,backpack剩余的size最小。
result[i][j] = Math.min(result[i - 1][j], result[i - 1][j - A[i - 1]]);
1 public class Solution { 2 /** 3 * @param m: An integer m denotes the size of a backpack 4 * @param A: Given n items with size A[i] 5 * @return: The maximum size 6 * 7 */ 8 public int backPack(int m, int[] A) { 9 if (A == null || A.length == 0) return m; 10 11 int[][] result = new int[A.length + 1][m + 1]; 12 for (int i = 0; i < result.length; i++) { 13 for (int j = 0; j <= m; j++) { 14 if (i == 0) { 15 result[i][j] = j; 16 continue; 17 } 18 if (j < A[i - 1]) { 19 result[i][j] = result[i - 1][j]; 20 } else { 21 result[i][j] = Math.min(result[i - 1][j], result[i - 1][j - A[i - 1]]); 22 } 23 } 24 } 25 return m - result[A.length][m]; 26 } 27 }
Given n items with size Ai and value Vi, and a backpack with size m. What‘s the maximum value can you put into the backpack?
Given 4 items with size [2, 3, 5, 7]
and value [1, 5, 2, 4]
, and a backpack with size 10
. The maximum value is 9
.
分析:
原理同上,转移方程如下:
maxValue[i][j] = Math.max(maxValue[i - 1][j], maxValue[i - 1][j - A[i]] + V[i]);
1 public class Solution { 2 /** 3 * @param m: An integer m denotes the size of a backpack 4 * @param A & V: Given n items with size A[i] and value V[i] 5 * @return: The maximum value 6 */ 7 public int backPackII(int m, int[] A, int V[]) { 8 if (m == 0 || A == null || A.length == 0 || V == null || V.length == 0) return 0; 9 10 int[][] maxValue = new int[A.length][m + 1]; 11 12 for (int i = 0; i < maxValue.length; i++) { 13 for (int j = 0; j < maxValue[0].length; j++) { 14 if (A[i] <= j) { 15 if (i == 0) { 16 maxValue[i][j] = V[i]; 17 } else { 18 maxValue[i][j] = Math.max(maxValue[i - 1][j], maxValue[i - 1][j - A[i]] + V[i]); 19 } 20 } else { 21 if (i != 0) { 22 maxValue[i][j] = maxValue[i - 1][j]; 23 } 24 } 25 } 26 } 27 return maxValue[maxValue.length - 1][maxValue[0].length - 1]; 28 } 29 }
参考请注明出处:cnblogs.com/beiyeqingteng/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5642218.html