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
Code (Java):2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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