前言
题目: 39. 组合总和
文档: 代码随想录------组合总和
编程语言: C++
解题状态: 没思路...
思路
还是回溯法,不过使用回溯法时,一定要将搜索过程抽象成树形结构。
代码
回溯法
cpp
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
res.clear();
path.clear();
sort(candidates.begin(), candidates.end());
backtracking(candidates, target, 0, 0);
return res;
}
};