-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode40.cpp
51 lines (50 loc) · 1.15 KB
/
leetcode40.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
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
void backtarck(vector<vector<int> >res, vector<bool> flag,vector<int> tmp, vector<int> candidates,int target)
{
if(target == 0)
{
bool found = false;
for(vector<vector<int> >::iterator it = res.begin(); it!= res.end();it++)
{
if(tmp == *it)
{
found = true;
break;
}
}
if(!found)
res.push_back(tmp);
return;
}
else if (target < 0)
{
return;
};
int max = 0;
for (int i = 0; i < tmp.size(); ++i)
{
if(tmp[i] > max)
max = tmp[i]
}
for (int i = 0; i < candidates.size(); ++i)
{
if(!flag[i] && candidates[i] >= max)
{
flag[i] = true;
tmp.push_back(candidates[i]);
combinationSum2Helper(ans, flag, tmp, candidates, target - candidates[i]);
tmp.pop_back();
flag[i] = false;
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> tmp;
vector<vector<int> >res;
vector<bool> flag(candidates.size(),false);
sort(candidates.begin(),candidates.end());
backtarck(res,flag,tmp,candidates,target);
return res;
}
};