forked from changqing16/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path40.cpp
More file actions
54 lines (49 loc) · 1.3 KB
/
40.cpp
File metadata and controls
54 lines (49 loc) · 1.3 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;
vector<vector<int>> ans;
int length;
void help(vector<int> &candidates, int cur[], int target, int loc, int len);
vector<vector<int>> combinationSum2(vector<int> &candidates, int target)
{
length = candidates.size();
sort(candidates.begin(), candidates.begin() + length);
if (target / candidates[0] == 0)
return ans;
int cur[target / candidates[0]];
for (int i = 0; i < length; i++)
{
if (i != 0 && candidates[i - 1] == candidates[i])
continue;
if (candidates[i] <= target)
{
cur[0] = candidates[i];
help(candidates, cur, target - candidates[i], i + 1, 1);
}
else
break;
}
return ans;
}
void help(vector<int> &candidates, int cur[], int target, int loc, int len)
{
if (target == 0)
{
vector<int> one(cur, cur + len);
ans.push_back(one);
return;
}
for (int i = loc; i < length; i++)
{
if (i != loc && candidates[i - 1] == candidates[i])
continue;
if (candidates[i] <= target)
{
cur[len] = candidates[i];
help(candidates, cur, target - candidates[i], i + 1, len + 1);
}
else
break;
}
}