-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombination_Sum_II.cpp
More file actions
37 lines (32 loc) · 1.01 KB
/
Copy pathCombination_Sum_II.cpp
File metadata and controls
37 lines (32 loc) · 1.01 KB
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
#include <vector>
#include <algorithm>
class Solution {
private:
std::vector<std::vector<int>> answer;
public:
std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
std::vector<int> curr;
helper(candidates, 0, 0, target, curr);
return answer;
}
void helper(std::vector<int>& candidates, int index, int sum, int target, std::vector<int>& currCombination) {
if (sum == target) {
answer.push_back(currCombination);
return;
}
if (sum > target) {
return;
}
int n = candidates.size();
for (int i=index; i<n; i++) {
currCombination.push_back(candidates[i]);
helper(candidates, i+1, sum+candidates[i], target, currCombination);
currCombination.pop_back();
while (i<n-1 && candidates[i] == candidates[i+1]) {
i++;
}
}
return;
}
};