原题链接:Leecode 39. 组合总和 dfs+回溯+剪枝
class Solution {
public:
vector<int> tmp;
vector<vector<int>> res;
void dfs(vector<int>& candidates, int target,int now)
{
if(target==0)
{
res.push_back(tmp);
return ;
}
if(target<candidates[0])
return ;
for(int i=now;i<candidates.size();i++)
{
if(target<candidates[i])
break;
else
{
tmp.push_back(candidates[i]);
dfs(candidates,target-candidates[i],i);
tmp.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
if(target<candidates[0])
return res;
dfs(candidates,target,0);
return res;
}
};