zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    阴影及定位
    选择器高级、样式及布局
    css的导入与基础选择器
    html知识
    ORM
    python实现进度条
    MySQL单表查询
    一、HTTP
    mysql4
    练习——MySQL
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4272300.html
Copyright © 2011-2022 走看看