-
Notifications
You must be signed in to change notification settings - Fork 481
/
0040.cpp
36 lines (35 loc) · 1.08 KB
/
0040.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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> path;
_combinationSum(candidates, target, 0, path, res);
return res;
}
private:
void _combinationSum(vector<int>& candidates, int target, int index, vector<int>& path, vector<vector<int>>& res)
{
if (target == 0)
{
res.push_back(path);
return;
}
if (!path.empty() and target < *(path.end() - 1)) return;
for (unsigned int i = index; i < candidates.size(); ++i)
{
if (i > index and candidates[i] == candidates[i - 1]) continue;
path.push_back(candidates[i]);
_combinationSum(candidates, target - candidates[i], i + 1, path, res);
path.pop_back();
}
}
};