1、
class Solution {
private:
vector<int>candidates;
vector<vector<int>>res;
vector<int>path;
void DFS(int start,int target)
{
if(target == 0)
{
res.push_back(path);
return ;
}
for(int i = start;
i < candidates.size() && target - candidates[i] >= 0;
i++)
{
if(i > start && candidates[i-1] == candidates[i])
{
continue;
}
path.push_back(candidates[i]);
DFS(i + 1, target - candidates[i]);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
this->candidates = candidates;
DFS(0,target);
return res;
}
};
2、
class Solution {
private:
vector<int>candidates;
vector<vector<int>>res;
vector<int>path;
void DFS(int start,int target,int sum)
{
if(target <= sum)
{
if(target == sum)
res.push_back(path);
return ;
}
for(int i = start;i < candidates.size();i++)
{
if(sum +candidates[i] > target)
{
break;
}
if(i > start && candidates[i-1] == candidates[i])
{
continue;
}
path.push_back(candidates[i]);
DFS(i+1, target, sum + candidates[i]);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
this->candidates = candidates;
DFS(0,target,0);
return res;
}
};