题目描述:
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Notice
You can not divide any item into small pieces.
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.
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[i]来表示size为i的时候,背包最大能装的size。那么对于i来说,遍历A,如果i - A[j]为正,表示i能装下A[j]的话,那么能装下的size就是dp[i - A[j]] + A[j]了。找到这类size的最大值,就是dp[i]的值。那么最终的答案就是dp[m].
Mycode(AC = 413ms):
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
int backPack(int m, vector<int> A) {
// write your code here
vector<int> dp(m + 1, 0);
for (int i = 0; i < A.size(); i++) {
for (int j = m; j >= 1; j--) {
if (j - A[i] >= 0) {
dp[j] = max(dp[j], dp[j - A[i]] + A[i]);
}
}
}
return dp[m];
}
};