-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum2.cpp
More file actions
57 lines (47 loc) · 1021 Bytes
/
combination_sum2.cpp
File metadata and controls
57 lines (47 loc) · 1021 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<vector<int> > ret;
ret.clear();
vector<int> tmp;
tmp.clear();
bool* flag=new bool[candidates.size()];
for(int i=0;i<candidates.size();i++)
{
flag[i]=false;
}
int sum=0;
int idx=0;
dfs(ret,tmp,candidates,flag,target, sum,idx);
return ret;
}
void dfs(vector<vector<int> > &ret, vector<int> &tmp, vector<int>& candidates, bool* flag, int &target, int &sum,int idx)
{
if(sum>=target)
{
if(sum==target)
{
ret.push_back(tmp);
}
return;
}
for(int i=idx;i<candidates.size(); i++)
{
if(i!=0&&candidates[i]==candidates[i-1]&&flag[i-1]==false)
{
idx++;
continue;
}
tmp.push_back(candidates[i]);
flag[i]=true;
sum+=candidates[i];
dfs(ret,tmp,candidates,flag,target,sum,idx+1);
tmp.pop_back();
flag[i]=false;
sum-=candidates[i];
idx++;
}
}
};