-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39. Combination Sum.cpp
38 lines (32 loc) · 979 Bytes
/
39. Combination Sum.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
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
set<vector<int>> s;
void helper(vector<int>& cand, int tar, vector<vector<int>>& ans, int sum, vector<int>& vec, int i){
if(i == cand.size() || sum > tar){
return;
}
if(sum == tar){
if(s.find(vec) == s.end()){
ans.push_back({vec});
s.insert(vec);
}
return;
}
sum += cand[i];
vec.push_back(cand[i]);
// Single Inclusion
helper(cand, tar, ans, sum, vec, i+1);
// Multiple Inclusion
helper(cand, tar, ans, sum, vec, i);
// Exclusion
sum -= cand[i]; // Backtracking Step
vec.pop_back(); // Backtracking Step
helper(cand, tar, ans, sum, vec, i+1);
}
vector<vector<int>> combinationSum(vector<int>& cand, int tar) {
vector<vector<int>> ans;
vector<int> vec;
helper(cand, tar, ans, 0, vec, 0);
return ans;
}
};