本质上还是用dfs去进行遍历,在实现的方式上却很耐人寻味,
class Solution {
public:
int n;
int k;
vector<vector<int>> result;
vector<int> tmp;
void dfs(int x){
if(tmp.size() == this->k){
this->result.push_back(this->tmp);
return;
}
for(int i = x ; i <= this->n - this->k + this->tmp.size() + 1; i ++ ){
this->tmp.push_back(i);
dfs(i + 1);
this->tmp.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
this->n = n;
this->k = k;
dfs(1);
return this->result;
}
};