-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path40. Combination Sum II.cpp
More file actions
30 lines (27 loc) · 911 Bytes
/
40. Combination Sum II.cpp
File metadata and controls
30 lines (27 loc) · 911 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
class Solution {
public:
void combination(int index, int target, vector<int>& arr,
vector<vector<int>>& answer, vector<int>& current) {
if (target == 0) {
answer.push_back(current);
return;
}
for (int i = index; i < arr.size(); i++) {
if (i > index && arr[i - 1] == arr[i])
continue;
if (arr[i] > target)
break;
current.push_back(arr[i]);
combination(i + 1, target - arr[i], arr, answer, current);
current.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> answer;
vector<int> current;
sort(candidates.begin(), candidates.end());
combination(0, target, candidates, answer, current);
return answer;
}
};