377. Combination Sum IV
- Total accepted:2547
- Total submissions:6581
- Difficulty:medium
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations this add up t o a positive integer target.
Example:
Nums = [1,2,3]target=4The possible combination ways is: (1,1,1,1)(1,1,2)(1,2,1)(1,3)(2,1,1)(2,2)(3,1Note that different sequences is counted asdifferent combinations. Therefore the output is 7.
Follow up:
What if negative numbers is allowed in the given array?
How does does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Idea: DP, can be top-down, can also be bottom-up. Suppose Values[i] represents the combination of I, apparently values[i]=values[i-nums[0]]+...+values[i-nums[n-1]] (n=nums.size ()).
Note that redundancy exists, for example, the following code does not remove redundancy:
1 classSolution {2 Public:3 intCOMBINATIONSUM4 (vector<int>& Nums,inttarget) {4 if(target<=0){5 return!Target;6 }7 intI,n=nums.size (), res=0;8 for(i=0; i<n;i++){9RES+=COMBINATIONSUM4 (nums,target-nums[i]);Ten } One returnRes; A } -};
So you can apply for memory first, and record the number of calculations already in the case.
Code:
Bottom-up:
1 classSolution {2 Public:3 intCOMBINATIONSUM4 (vector<int>& Nums,inttarget) {4 //local domain parameter request, not initialized, may not be 05 //For example6 //int *values=new Int[target];7 //The value of each number of values array is any value at this time! 8vector<int> Values (target+1);9values[0]=1;Ten for(intI=1; i<=target;i++){ One for(intj=0; J<nums.size (); j + +){ A inttemp=i-Nums[j]; - if(temp>=0){ -values[i]=values[i]+Values[temp]; the } - } - } - returnValues[target]; + } -};
From top to bottom:
https://leetcode.com/problems/distinct-subsequences/
Leetcode 377. Combination Sum IV