Given an integer array nums
with all positive numbers and no duplicates, find the number of possible combinations the ad D up to a positive integer target
.
Notice
The different sequences is counted as different combinations.
Has you met this question in a real interview?Yes
Example
Given nums = [1, 2, 4]
, target =4
The possible combination ways are:[1, 1, 1, 1][1, 1, 2][1, 2, 1][2, 1, 1][2, 2][4]
Return6
Don't quite understand this title called What is called Backpack,leetcode on the original topic, please see my previous blog combination Sum Iv.
Solution One:
classSolution { Public: /** * @param nums an integer array and all positive numbers, no Duplicates * @param target an integer * @ret Urn an integer*/ intBACKPACKVI (vector<int>& Nums,inttarget) {Vector<int> dp (target +1,0); dp[0] =1; for(inti =1; I <= target; ++i) { for(Auto a:nums) {if(A <=i) {Dp[i]+ = Dp[i-a]; } } } returnDp.back (); }};
Solution Two:
classSolution { Public: /** * @param nums an integer array and all positive numbers, no Duplicates * @param target an integer * @ret Urn an integer*/ intBACKPACKVI (vector<int>& Nums,inttarget) {Vector<int> dp (target +1,0); dp[0] =1; Sort (Nums.begin (), Nums.end ()); for(inti =1; I <= target; ++i) { for(Auto a:nums) {if(A > i) Break; Dp[i]+ = Dp[i-a]; } } returnDp.back (); }};
[Lintcode] Backpack VI Backpack Six