-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0039.cpp
More file actions
executable file
·37 lines (33 loc) · 807 Bytes
/
LC0039.cpp
File metadata and controls
executable file
·37 lines (33 loc) · 807 Bytes
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
29
30
31
32
33
34
35
36
37
/*
Problem Statement: https://leetcode.com/problems/combination-sum/
Time: O(targetⁿ)
Space: O(targetⁿ)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int n = candidates.size();
vector<int> comb;
vector<vector<int>> combs;
// for optimization
sort(candidates.begin(), candidates.end());
// helper function
function<void(int, int)> dfs = [&](int pos, int sum) {
if (sum >= target) {
if (sum == target)
combs.push_back(comb);
return;
}
for (int i = pos; i < n; i++) {
if (sum + candidates[i] > target)
break;
comb.push_back(candidates[i]);
dfs(i, sum + candidates[i]);
comb.pop_back();
}
};
dfs(0, 0);
return combs;
}
};