Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Example
Example 1:
Input: [3,4,8,5], backpack size=10
Output: 9
Example 2:
Input: [2,3,5,7], backpack size=12
Output: 12
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.
Notice
You can not divide any item into small pieces.
思路:用f[i][j] 表示用前i个物品能否装满容量为j的情况,能true,不能false;最后再从右往左扫描一次,第一个true就是最大的容量能够装的;注意m == 0 的时候,所有的是dp[i][0] 是true,不装就完事了,是可以满足size = 0 的情况的;
public class Solution {
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
public int backPack(int m, int[] A) {
int n = A.length;
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for(int j = 1; j <= m; j++) {
dp[0][j] = false;
}
for(int i = 1; i <= n; i++) {
for(int j = 0; j <= m; j++) {
dp[i][j] = dp[i - 1][j];
if(j - A[i - 1] >= 0) {
dp[i][j] |= dp[i - 1][j - A[i - 1]];
}
}
}
int max = 0;
for(int j = m; j >= 0; j--) {
if(dp[n][j]) {
max = j;
break;
}
}
return max;
}
}