class Solution {
public:
void DFS(int start,int cursum,int target,vector<int> &candidates,vector<int> &path,vector<vector<int>> &ret)
{
if(cursum==target)
{
ret.push_back(path);
return;
}
for(int i=start;i<candidates.size();i++)
{
cursum+=candidates[i];
if(cursum>target)
return;
path.push_back(candidates[i]);
DFS(i,cursum,target,candidates,path,ret);
path.pop_back();
cursum-=candidates[i];
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<int> path;
vector<vector<int>> ret;
DFS(0,0,target,candidates,path,ret);
return ret;
}
};
public:
void DFS(int start,int cursum,int target,vector<int> &candidates,vector<int> &path,vector<vector<int>> &ret)
{
if(cursum==target)
{
ret.push_back(path);
return;
}
for(int i=start;i<candidates.size();i++)
{
cursum+=candidates[i];
if(cursum>target)
return;
path.push_back(candidates[i]);
DFS(i,cursum,target,candidates,path,ret);
path.pop_back();
cursum-=candidates[i];
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<int> path;
vector<vector<int>> ret;
DFS(0,0,target,candidates,path,ret);
return ret;
}
};