- 分析
典型的回溯算法,直接套用回溯的算法框架 - 代码
class Solution {
public:
vector<vector<int>> vec;
vector<vector<int>> combine(int n, int k) {
vector<int> temp;
backtrack(n, k, 1, temp);
return vec;
}
void backtrack(int n, int k, int start,vector<int>& temp){
if(temp.size() == k){
vec.push_back(temp);
return;
}
for(int i = start; i <= n; i++){
temp.push_back(i);
backtrack(n, k, i + 1, temp);
temp.pop_back();
}
}
};