img

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
class Solution {

public:
vector<vector<int>> res;
void dfs(vector<int>& candidates,vector<int>& ans,int sum,int pos, int &target){

ans.push_back(candidates[pos]);
if(sum+candidates[pos]==target) res.push_back(ans);
else if(sum+candidates[pos]<target){

for(int i=pos+1;i<candidates.size();i++){

if(i>pos+1 && candidates[i]==candidates[i-1]) continue;
dfs(candidates,ans,sum+candidates[pos],i,target);
}
}
ans.pop_back();
return ;
}

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {

sort(candidates.begin(),candidates.end());
vector<int> ans;
for(int i=0;i<candidates.size();i++){

if(i>0 && candidates[i]==candidates[i-1]) continue;
dfs(candidates,ans,0,i,target); //每一次dfs都把以i这个元素作为第一个元素的组合都找出来了,那么后面再以i这个元素作为第一个元素就是重复的
}
return res;
}
};