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