Backpack
Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack?
Example
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.
Note
You can not divide any item into small pieces.
Challenge
O(n x m) time and O(m) memory.
O(n x m) memory is also acceptable if you do not know how to optimize memory.
解题思路:DP
boolean d[i][j]: For the first i items, can we fill a backpack of size j? true or false.(表示选择前i项中若干个看能不能组合成j)
d[i][j] = d[i-1][j] || (j>=A[i-1] && d[i-1][j-A[i-1]]).
d[0][0] = true;
We can use 1D array to perform the DP.
d[j] = d[j] || d[j-A[i-1]].
NOTE: for 1D array, the j must be decreased from m to 0 rather increasing from 0 to m!
public int backPack(int m, int[] pack) {
// write your code here
boolean[][] res = new boolean[pack.length+1][m+1];
res[0][0] = true;
for (int i=1; i<=pack.length; i++) {
for (int j=0; j<=m; j++) {
res[i][j] = res[i-1][j] || (j-pack[i-1]>=0 && res[i-1][j-pack[i-1]]);
}
}
for (int j=m; j>=0; j--) {
if (res[pack.length][j]) return j;
}
return 0;
}