首页 > 其他 > 详细

lintcode-medium-Backpack II

时间:2016-03-14 15:16:04      阅读:277      评论:0      收藏:0      [点我收藏+]

Given n items with size Ai and value Vi, and a backpack with size m. What‘s the maximum value can you put into the backpack?

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.

 

和上一题差不多,这题里动态规划用的数组类型是int[],用来记录背包里放容积为k的物体时,这些物体的最大价值

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[]) {
        // write your code here
        
        if(A == null || A.length == 0)
            return 0;
        
        int[] dp = new int[m + 1];
        int result = 0;
        
        dp[0] = 0;
        
        for(int i = 0; i < A.length; i++){
            for(int j = m ; j >= A[i]; j--){
                dp[j] = Math.max(dp[j], dp[j - A[i]] + V[i]);
            }
        }
        
        for(int i = 0; i < dp.length; i++){
            if(dp[i] > result)
                result = dp[i];
        }
        return result;
    }
}

 

lintcode-medium-Backpack II

原文:http://www.cnblogs.com/goblinengineer/p/5275761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!