Skip to content

Commit 63026ae

Browse files
committed
Create: 0377-combination-sum-iv.cpp
1 parent 3c00e2a commit 63026ae

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cpp/0377-combination-sum-iv.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Given an array of distinct integers nums and a target integer 'target',
3+
return the number of possible combinations that add up to target.
4+
5+
Ex. nums = [1,2,3] target = 4
6+
Possible Combinations: (1,1,1,1) (1,1,2) (1,2,1) (1,3) (2,1,1,)
7+
(2,2) (3,1).
8+
So, total number of combinations possible is 7.
9+
10+
Time: O(n * m)
11+
Space: O(m)
12+
*/
13+
14+
class Solution {
15+
public:
16+
int combinationSum4(vector<int>& nums, int target) {
17+
sort(nums.begin(), nums.end());
18+
vector<unsigned int> dp(target+1, 0);
19+
dp[0] = 1;
20+
for(int total=1; total<=target; total++) {
21+
for(int i=0; i<nums.size(); i++) {
22+
if(nums[i] <= total) dp[total] += dp[total - nums[i]];
23+
else break;
24+
}
25+
}
26+
return dp[target];
27+
}
28+
};

0 commit comments

Comments
 (0)