Wednesday, April 10, 2019

Lintcode 563. Backpack V

Given n items with size nums[i] which an integer array and all positive numbers. An integer target denotes the size of a backpack. Find the number of possible fill the backpack.
Each item may only be used once

Example

Given candidate items [1,2,3,3,7] and target 7,
A solution set is: 
[7]
[1, 3, 3]
return 2
Code (Java):
public class Solution {
    /**
     * @param nums: an integer array and all positive numbers
     * @param target: An integer
     * @return: An integer
     */
    public int backPackV(int[] nums, int target) {
        if (nums == null || nums.length == 0 || target < 0) {
            return 0;
        }
        
        int[] dp = new int[target + 1];
        dp[0] = 1;
        
        for (int i = 1; i <= nums.length; i++) {
            for (int j = target; j >= 1; j--) {
                int ans = dp[j];
                if (j - nums[i - 1] >= 0) {
                    ans += dp[j - nums[i - 1]];
                }
                
                dp[j] = ans;
            }
        }
        
        return dp[target];
    }
}

No comments:

Post a Comment