思路: 简单回溯。
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int> > res;
vector<int> combination;
sort(candidates.begin(), candidates.end());
DFS(candidates, target, res, combination, 0);
return res;
}
void DFS(vector<int>& candidates, int target, vector<vector<int> > &res, vector<int> &combination, int step)
{
if (target == 0)
{
res.push_back(combination);
return;
}
for(int i = step; i < candidates.size() && target >= candidates[i]; i++)
{
combination.push_back(candidates[i]);
DFS(candidates, target-candidates[i], res, combination, i);
combination.pop_back();
}
}
};