forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0377-combination-sum-iv.cpp
28 lines (25 loc) · 770 Bytes
/
0377-combination-sum-iv.cpp
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
/*
Given an array of distinct integers nums and a target integer 'target',
return the number of possible combinations that add up to target.
Ex. nums = [1,2,3] target = 4
Possible Combinations: (1,1,1,1) (1,1,2) (1,2,1) (1,3) (2,1,1,)
(2,2) (3,1).
So, total number of combinations possible is 7.
Time: O(n * m)
Space: O(m)
*/
classSolution {
public:
intcombinationSum4(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<unsignedint> dp(target+1, 0);
dp[0] = 1;
for(int total=1; total<=target; total++) {
for(int i=0; i<nums.size(); i++) {
if(nums[i] <= total) dp[total] += dp[total - nums[i]];
elsebreak;
}
}
return dp[target];
}
};