这道题目应当是一类题目,这类题目有个统一的解法—回溯法(backtracking)
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> combination;
sort(candidates.begin(),candidates.end());
combinationSum(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum(vector<int> &candidates, int target, vector<vector<int> > &res, vector<int> &combination, int begin)
{
if(!target)
{
res.push_back(combination);
return;
}
for(int i = begin;i < candidates.size() && target >= candidates[i];i++)
{
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
}
}
};
对回溯算法的一个浅显理解有点类似于暴力破解。
回溯法不断的试错,如果当前方法不可行则回退一步或者几步,然后继续尝试不同的答案,直到找到正确答案。