题目描述
2.
以下是回溯算法的模版
class Solution {
private:
vector<vector<int>> res;
vector<int> path;//这个变量名还是设为path更合适
void backtrace(int n, int k, int startindex){
//递归结束条件,这个是根据问题要求修改的
if(path.size() == k){
//找到了一个合适的组合
res.push_back(path);
return ;
}
//回溯过程
for(int i = startindex; i <= n - (k - path.size()) + 1; i++){
path.push_back(i);
//向下递归的操作可以看作一个子问题
backtrace(n,k,i+1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
res.clear();
path.clear();
backtrace(n,k,1);
return res;
}
};
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtrace(int n, int k, int startindex){
if(path.size() == k && accumulate(path.begin(), path.end(), 0) == n){
res.push_back(path);
return ;
}
for(int i = startindex; i <= 9; i++){
path.push_back(i);
backtrace(n,k,i+1);
path.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
res.clear();
path.clear();
backtrace(n, k, 1);
return res;
}
};
标签:return,int,res,startindex,力扣,算法,回溯,backtrace,path
From: https://www.cnblogs.com/satsuki26681534/p/18057915