-
Notifications
You must be signed in to change notification settings - Fork 28
/
Combination_Sum_II.cpp
43 lines (42 loc) · 1.63 KB
/
Combination_Sum_II.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
39
40
41
42
43
class Solution {
public:
void combinationSum2Utils(int indx, int sum, vector<int> &candidates, vector<int> &solution, vector<vector<int> > &result) {
if(indx == candidates.size()) {
if(sum == 0) result.push_back(solution);
return;
}
if(sum == 0) {
result.push_back(solution);
return;
}
int prev = -1;
for(int i = indx; i < candidates.size(); ++i) {
if(sum - candidates[i] >= 0) {
if(prev == candidates[i]) continue;
solution.push_back(candidates[i]);
combinationSum2Utils(i + 1, sum - candidates[i], candidates, solution, result);
solution.pop_back();
prev = candidates[i];
} else {
break;
// return;
}
}
}
vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
vector<vector<int> > result;
vector<int> solution;
if(candidates.size() < 0) return result;
sort(candidates.begin(), candidates.end());
combinationSum2Utils(0, target, candidates, solution, result);
#if 0
for_each(result.begin(), result.end(), [](vector<int>& solution) {
for_each(solution.begin(), solution.end(), [](int item) {
cout << item << " ";
});
cout << endl;
});
#endif
return result;
}
};