Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
[Thoughts]
这是一个DP问题。对于任意个一个数值n
DP[n] = ∑ DP[target - nums[i]] 0<= i< n
[Code]
1: int combinationSum4(vector<int>& nums, int target) {
2: vector<int> count(target +1, 0);
3:
4: count[0] =1;
5: for(int i =1; i<=target; i++) {
6: for(int j =0; j< nums.size(); j++) {
7: if(i - nums[j] >=0) {
8: count[i] += count[i-nums[j]];
9: }
10: }
11: }
12:
13: return count[target];
14: }
No comments:
Post a Comment