Topic Address:
https://www.lintcode.com/problem/backpack/description
Knapsack problem. Given an array represents the volume of each item, and a volume up to ask how much volume can be filled. Dynamic Programming. Assume
is a front
th volume of goods to be stuffed
, the maximum number of volume can be stuffed. So there are two cases:
1, and hold the first
items, then the volume is up to plug
;
2, caving
items, then the volume is up to plug
.
So only need to compare both of whom can be large. code show as below:
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) {
// write your code here
if (A == null || A.length == 0) {
return 0;
}
// dp[i][j]表示从前i个物品拿若干物品塞进容积为j的背包,最多能塞多少体积
int[][] dp = new int[A.length][m + 1];
// 初始化第0行
for (int j = A[0]; j <= m; j++) {
dp[0][j] = A[0];
}
for (int i = 1; i < A.length; i++) {
for (int j = 0; j <= m; j++) {
dp[i][j] = dp[i - 1][j];
if (j >= A[i]) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - A[i]] + A[i]);
}
}
}
return dp[A.length - 1][m];
}
}
Time and space complexity 。
Next, consider space optimization. Notes that each calculation when only uses the row immediately above the element, and the element row on the left. So consider row rollover. Note that the update column when the need to update from right to left.
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) {
// write your code here
if (A == null || A.length == 0) {
return 0;
}
int[] dp = new int[m + 1];
for (int j = A[0]; j <= m; j++) {
dp[j] = A[0];
}
for (int i = 1; i < A.length; i++) {
for (int j = m; j >= A[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - A[i]] + A[i]);
}
}
return dp[m];
}
}
The same time complexity, space becomes .