原题链接:Leetcode 77. 组合
回溯1:枚举下一个数选哪个
class Solution {
public:
vector<vector<int>> res;
void dfs(int l, int r, int k, vector<int>& path) {
if (k == 0) {
res.push_back(path);
return;
}
if (r - l + 1 < k)
return; // 剪枝
for (int i = l; i <= r; i++) {
path.push_back(i);
dfs(i + 1, r, k - 1, path);
path.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<int> path;
dfs(1, n, k, path);
return res;
}
};
回溯2:选 / 不选
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(int n,int k,int index){
if(k==0){
res.push_back(path);
return ;
}
if(n-index+1<k) return ;
if(index<=n){
path.push_back(index);
dfs(n,k-1,index+1);
path.pop_back();
dfs(n,k,index+1);
}
}
vector<vector<int>> combine(int n, int k) {
dfs(n,k,1);
return res;
}
};