给出n个物品的体积A[i]和其价值V[i],将他们装入一个大小为m的背包,最多能装入的总价值有多大?
您在真实的面试中是否遇到过这个题?
典型的01背包问题,动态规划解决。
状态转移方程:
ans[i][j] = max ( ans[i-1][j-A[i-1]] + V[i-1], ans[i-1][j-1] ) 当(j >= V[i])时。
ans[i][j] = ans[i-1][j] 当(j < V[i]) 时
ans[i][j] = 0 当(i==0 || j == 0时)
这里需要注意ans数组共有(n+1) * (m+1)个元素。
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A & V: Given n items with size A[i] and value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> A, vector<int> V) {
// write your code here
int n = A.size();
vector<vector<int> > ans(n+1, vector<int>(m+1));
for(int i=0; i<=n; i++){
for(int j=0; j<=m; j++){
if(i==0 || j==0){
ans[i][j] = 0;
}
else {
if(j >= A[i-1]){
ans[i][j] = max((ans[i-1][j-A[i-1]] + V[i-1]), ans[i-1][j]);
}
else{
ans[i][j] = ans[i-1][j];
}
}
}
}
return ans[n][m];
}
};
CSDN上的一位朋友讲解的背包问题感觉思路很清晰,链接在这。