lintcode-medium-Backpack

Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?

If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 5], so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7]so that we can fulfill the backpack.

You function should return the max size we can fill in the given backpack.

 

这题是个动态规划的题,用一个boolean数组记录背包中能否装入size=k的物体

两层循环:

第一层循环遍历数组A

第二层循环从背包最大容积一直遍历到A[i],如果dp[j -A[i]]为true,说明这次循环之前,背包中可以加入体积为j-A[i]的物体,再加入体积为A[i]的物体,现在dp[j]也应该为true。或者dp[j]已经为true了,应该保留这个结果。所以状态转移方程应为dp[j] = dp[j] || dp[j - A[i]]

最后从dp[]末尾开始遍历,只要遇到值为true的就返回index

public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    public int backPack(int m, int[] A) {
        // write your code here
        
        if(A == null || A.length == 0)
            return 0;
        
        boolean[] dp = new boolean[m + 1];
        
        dp[0] = true;
        
        for(int i = 0; i < A.length; i++){
            for(int j = m; j >= A[i]; j--){
                dp[j] = dp[j] || dp[j - A[i]];
            }
        }
        
        for(int i = m; i >= 0; i--){
            if(dp[i])
                return i;
        }
        return 0;
    }
}

 

posted @ 2016-03-14 14:48  哥布林工程师  阅读(187)  评论(0编辑  收藏  举报