Skip to content

Commit

Permalink
Create: 0377-combination-sum-iv.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
ashutosh2706 committed Feb 11, 2023
1 parent 3c00e2a commit 63026ae
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions cpp/0377-combination-sum-iv.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)
*/

class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<unsigned int> 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]];
else break;
}
}
return dp[target];
}
};

0 comments on commit 63026ae

Please sign in to comment.