您的位置:首页 > 其它

Lintcode: Backpack II

2015-02-04 14:36 183 查看
Given n items with size A[i] and value V[i], and a backpack with size m. What's the maximum value can you put into the backpack?
Note
You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.

Example
Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.


这道题还是跟Backpack有大不一样之处

用子问题定义状态:即f[i][v]表示前 i 件物品恰放入一个容量为 j 的背包可以获得的最大价值。则其状态转移方程便是:

f[i][j] = max{f[i-1][j], j>=A[i-1]? f[i-1][j-A[i-1]]+V[i-1] : 0}

public class Solution {
/**
* @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
*/
public int backPackII(int m, int[] A, int V[]) {
int[][] res = new int[A.length+1][m+1];
res[0][0] = 0;
for (int i=1; i<=A.length; i++) {
for (int j=0; j<=m; j++) {
if (j - A[i-1] < 0)
res[i][j] = res[i-1][j];
if (j - A[i-1] >= 0) {
res[i][j] = Math.max(res[i-1][j], res[i-1][j-A[i-1]]+V[i-1]);
}
}
}

return res[A.length][m];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: