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]; } }
相关文章推荐
- LintCode Backpack II(背包II)
- lintcode-搜索二维矩阵II-38
- LintCode python 小白6-丑数 II
- lintcode-117-跳跃游戏 II
- LintCode: Paint House II
- lintcode 两数组的交II
- LintCode 整数排序 II
- lintcode Find the Missing Number II
- lintcode coins-in-a-line-ii 硬币排成线ii
- lintcode 中等题:N Queens II N皇后问题 II
- LintCode-381.螺旋矩阵 II
- lintcode 中等题:search in rotated sorted arrayII 搜索旋转排序数组II
- LintCode-数字组合 II
- lintcode:两数组的交 II
- LintCode "Find Peak Element II"
- LINTCODE——房屋染色II
- lintcode:Longest Increasing Continuous subsequence II
- lintcode-落单的数 II
- LintCode lowest common ancestor ii has parent point
- LintCode Word Break II