- 分析
套用回溯模板,回溯算法都是改一下结束条件,改一下做选择的条件即可。 - 代码
class Solution {
public:
vector<vector<int>> vec;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> temp;
backtrack(candidates, 0,temp, 0, target);
return vec;
}
void backtrack(vector<int>& candidates, int start, vector<int>& temp, int sum, int target){
if(sum == target){
vec.push_back(temp);
return;
}
for(int i = start; i < candidates.size(); i++){
int data = candidates[i];
if(sum + data > target) continue;
temp.push_back(data);
backtrack(candidates, i, temp, sum + data, target);
temp.pop_back();
}
}
};