码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode: Backpack II

时间:2015-02-04 16:11:44      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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]? f[i-1][j-A[i]]+V[i] : 0}

这里 j 变成了背包容量,而不是上一道题中的item总size,所以这里 j 只需要大于等于A[i]就可以加V,而不需要前i-1个item size为j - A[i]

 1 public class Solution {
 2     /**
 3      * @param m: An integer m denotes the size of a backpack
 4      * @param A & V: Given n items with size A[i] and value V[i]
 5      * @return: The maximum value
 6      */
 7     public int backPackII(int m, int[] A, int V[]) {
 8         int[][] res = new int[A.length+1][m+1];
 9         res[0][0] = 0;
10         for (int i=1; i<=A.length; i++) {
11             for (int j=0; j<=m; j++) {
12                 if (j - A[i-1] < 0)
13                     res[i][j] = res[i-1][j];
14                 if (j - A[i-1] >= 0) {
15                     res[i][j] = Math.max(res[i-1][j], res[i-1][j-A[i-1]]+V[i-1]);
16                 }
17             }
18         }
19         int maxNum = 0;
20         for (int i=0; i<=m; i++) {
21             maxNum = Math.max(maxNum, res[A.length][i]);
22         }
23         return maxNum;
24     }
25 }

 

Lintcode: Backpack II

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4272300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!