Backpack1-01
Example
Note
Code
// 一种解法
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
int n = A.length;
int[][] dp = new int[n + 1][m + 1];
//n is numbers of item, m is size, value is max No.items
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= m; ++j) {
dp[i + 1][j] = dp[i][j];
if (j >= A[i]) {
dp[i + 1][j] = Math.max(dp[i][j],
dp[i][j - A[i]] + A[i]);
}
}
}
return dp[n][m];
}
}
// * O(m) 空间复杂度的解法
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 f[] = new int[m + 1];
for (int i = 0; i < A.length; i++) {
for (int j = m; j >= A[i]; j--) {
f[j] = Math.max(f[j], f[j - A[i]] + A[i]);
}
}
return f[m];
}
}Last updated