lintcoe 92 · Backpack
/*
m denotes the size of a backpack
dp[i][j] = can pre num i to fit sum = j or not, use boolean
if (j >= A[i-1]) {
dp[i][j] = dp[i-1][j] || dp[i-1][j - A[i-1]];
} else {
dp[i][j] = dp[i-1][j];
}
*/
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]; // item from 0~n, size from 0~m
dp[0][0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (j >= A[i-1]) {
// choose or not choose
dp[i][j] = dp[i-1][j] || dp[i-1][j - A[i-1]];
} else {
// j < A[i-1], size of a backpack j < item size, can't choose
dp[i][j] = dp[i-1][j];
}
}
}
// find the max weight which status is true(can put in pack)
// from weight m to find true status
for (int i = m; i >= 0; i--) {
if (dp[n][i]) {
return i;
}
}
return -1;
}
}
python
Last updated