在n个物品中挑选若干物品装入背包,最多能装多满?假设背包的大小为m,每个物品的大小为A[i]
您在真实的面试中是否遇到过这个题?
Yes
样例
如果有4个物品[2, 3, 5, 7]
如果背包的大小为11,可以选择[2, 3, 5]装入背包,最多可以装满10的空间。
如果背包的大小为12,可以选择[2, 3, 7]装入背包,最多可以装满12的空间。
函数需要返回最多能装满的空间大小。
注意
标签
Expand
你不可以将物品进行切割。
相关题目 Expand
分析:这题就真的是直接上01背包的模板就行啦
代码:
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 *dp = new int[m+1];
fill(dp,dp+m+1,-1);
dp[0]=0;
for(auto x:A)
{
for(int i=m;i>=x;i--)
{
if(dp[i-x]!=-1)
dp[i]=1;
}
}
int ret = m;
while(dp[ret]==-1)
ret--;
delete[] dp;
return ret;
}
};