• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: Backpack II

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}

 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 
20         return res[A.length][m];
21     }
22 }

 

posted @ 2015-02-04 14:36  neverlandly  阅读(2141)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3