【Lintcode】92. Backpack

Topic Address:

https://www.lintcode.com/problem/backpack/description

Knapsack problem. Given an array represents the volume of each item, and a volume up to ask how much volume can be filled. Dynamic Programming. Assume f [ i ] [ j ] f[i][j] is a front i i th volume of goods to be stuffed j j , the maximum number of volume can be stuffed. So there are two cases:
1, and hold the first i i items, then the volume is up to plug f [ i 1 ] [ j ] f[i-1][j] ;
2, caving i i items, then the volume is up to plug f [ i 1 ] [ j A [ i ] ] + A [ i ] f[i-1][j-A[i]]+A[i] .
So only need to compare both of whom can be large. code show as below:

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;
        }
        // dp[i][j]表示从前i个物品拿若干物品塞进容积为j的背包,最多能塞多少体积
        int[][] dp = new int[A.length][m + 1];
        // 初始化第0行
        for (int j = A[0]; j <= m; j++) {
            dp[0][j] = A[0];
        }
    
        for (int i = 1; i < A.length; i++) {
            for (int j = 0; j <= m; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j >= A[i]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - A[i]] + A[i]);
                }
            }
        }
        
        return dp[A.length - 1][m];
    }
}

Time and space complexity O ( n m ) O(nm)

Next, consider space optimization. Notes that each calculation d p [ i ] [ j ] dp[i][j] when only uses the row immediately above the element, and the element row on the left. So consider row rollover. Note that the update column when the need to update from right to left.

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;
        }
    
        int[] dp = new int[m + 1];
        for (int j = A[0]; j <= m; j++) {
            dp[j] = A[0];
        }
    
        for (int i = 1; i < A.length; i++) {
            for (int j = m; j >= A[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - A[i]] + A[i]);
            }
        }
    
        return dp[m];
    }
}

The same time complexity, space becomes O ( m ) Man) .

Published 114 original articles · won praise 0 · Views 3502

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/104093402