-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum2.cpp
40 lines (35 loc) · 1023 Bytes
/
CombinationSum2.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
#include <bits/stdc++.h>
#include "../utilities.h"
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& arr, int target) {
vector<vector<int>> ans;
vector<int> ds;
size_t s = arr.size();
function<void(int, int)> findCombinations;
findCombinations = [&findCombinations, &ds, &ans, &arr, s](int idx, int target) mutable -> void {
if(target==0) {
ans.push_back(ds);
return;
}
for(int i = idx;i < s;i++) {
if(i> idx && arr[i] == arr[i-1]) continue;
if(arr[i] > target) break;
ds.push_back(arr[i]);
findCombinations(i + 1, target - arr[i]);
ds.pop_back();
}
};
findCombinations(0, target);
return ans;
}
};
int main() {
vector<int> test1{10, 1, 2, 7, 6, 1, 5};
Solution s;
sort(test1.begin(), test1.end());
vector<vector<int>> ans = s.combinationSum2(test1, 8);
cout << ans;
return 0;
}