LintCode Brush title - knapsack problem

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/kingslave1/article/details/78157454

Problem Description:

Select a few items into the backpack in the n items, you can hold up to how full? Suppose backpack size m, the size of each item of A [i].

Note that the items indivisible.

Example:

If there are four items [2, 3, 5, 7]

If the size of the backpack 11 , may be selected [2, 3, 5] into a bag, filled with up to 10 spaces.

If the size of the backpack 12 , may be selected [2, 3, 7] into a bag, filled with up to 12 spaces.

Function needs to return up to fill the space.

answer:

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[] array) {	
        int [][]dp=new int[array.length][m+1];
		for(int i=0;i<array.length;i++) {
			dp[i][0]=0;
		}
		for(int j=0;j<m+1;j++) {
			if(j>=array[0]) {
				dp[0][j]=array[0];
			}
		}
		
		for(int i=1;i<array.length;i++) {
			for(int j=1;j<m+1;j++) {
				if(j>=array[i]) {
					dp[i][j]=dp[i-1][j]>dp[i-1][j-array[i]]+array[i]?dp[i-1][j]:dp[i-1][j-array[i]]+array[i];
				}else {
					dp[i][j]=dp[i-1][j];
				}
			}
		}
		return dp[array.length-1][m];
	}
}



Guess you like

Origin blog.csdn.net/kingslave1/article/details/78157454