Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Example
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.
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.
1.方法1
背包问题其实就是多阶段动态规划问题。
理解1:
cnt[i][j]表示1~i个物体,装到容量为j的包里的最大重量(这里为容量)。
如果j>=A[i-1]
cnt[i][j]=max(cnt[i-1][j],cnt[i-1][j-A[i-1]]+A[i-1]);
否则
cnt[i][j]=cnt[i-1][j];
为什么递推公式是这样的?
可以想象成DAG,
第i层的cnt[i][j]与第i-1层相关联的叶子为cnt[i-1][j],cnt[i-1][j-A[i-1]]。
理解2:
将前i件物品放到容量为v的背包中,若我们只考虑第i件物品时,它有两种选择,放或者不放。
1) 如果第i件物品不放入背包中,那么问题就转换为:将前i - 1件物品放到容量为v的背包中,带来的收益f[i - 1][v]
2) 如果第i件物品能放入背包中,那么问题就转换为:将前i - 1件物品放到容量为v - weight[i]的背包中,带来的收益f[i - 1][v - weight[i]] + cost[i]
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
int len=A.size();
vector<vector<int> > cnt(len+1,vector<int>(m+1,0));
for(int i=1;i<=len;i++){
for(int j=0;j<=m;j++){
cnt[i][j]=cnt[i-1][j];
if(j>=A[i-1]){
cnt[i][j]=max(cnt[i-1][j],cnt[i-1][j-A[i-1]]+A[i-1]);
}
}
}
return cnt[len][m];
}
};
这个提交Memory Limit Exceeded
改成一维数组
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
int len=A.size();
//vector<vector<int> > cnt(len+1,vector<int>(m+1,0));
vector<int> cnt(m+1,0);
for(int i=1;i<=len;i++){
/*注意此时j从m开始,滚动数组*/
for(int j=m;j>=0;j--){
if(j>=A[i-1]){
cnt[j]=max(cnt[j],cnt[j-A[i-1]]+A[i-1]);
}
}
}
return cnt[m];
}
};