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.
     
    Solution:
     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 len = A.length;
     9         if (len==0) return -1;
    10 
    11         int[][] maxVal = new int[len+1][m+1];
    12         for (int i=0;i<=m;i++)
    13             maxVal[0][i]=0;
    14 
    15         for (int i = 1; i<=len;i++)
    16             for (int s=0; s<=m; s++){
    17                 maxVal[i][s] = maxVal[i-1][s];
    18                 if (s>=A[i-1] && maxVal[i][s]<maxVal[i-1][s-A[i-1]]+V[i-1])
    19                     maxVal[i][s] = maxVal[i-1][s-A[i-1]]+V[i-1];
    20                 }
    21 
    22         int max = 0;
    23         for (int i=0;i<=m;i++)
    24             if (maxVal[len][i]>max) max = maxVal[len][i];
    25 
    26         return max;
    27         
    28 
    29     }
    30 }
  • 相关阅读:
    shell编程之 ()[] {}
    mysql环境搭建
    CSS布局基础——BFC
    Java线程
    chrome developer tool—— 断点调试篇
    JavaScript技巧[转载]
    如何在github中创建演示demo
    rem在响应式布局中的应用
    javascript模块化
    浏览器客户端的数据存储
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4196877.html
Copyright © 2011-2022 走看看