题目如下:
解题思路:
采用 递归 + 回溯 的方式,下面这个图对解题思路解释的很清楚(原图地址)。
代码如下:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res; //存放结果
vector<int> temp; //存放中间结果
sort(candidates.begin(), candidates.end());
computeSum(0, target, candidates, temp, res);
return res;
}
void computeSum(int start, int target, vector<int>& candidates, vector<int>& temp, vector<vector<int>>& res){
int n = candidates.size();
for(int i = start; i < n; i++){
if(target > 0){
temp.push_back(candidates[i]);
computeSum(i, target-candidates[i], candidates, temp, res);
temp.pop_back();
}
//回溯
else if(target == 0){
res.push_back(temp);
return;
}
else
return;
}
}
};