方法:递归
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void solve(int n, int k, int idx) {
if (path.size() == k) {
res.push_back(path);
return ;
}
for (int i = idx; i <= n - (k-path.size()) + 1; ++i) {
path.push_back(i);
solve(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
res.clear();
solve(n, k, 1);
return res;
}
};
$时间复杂度O(),空间复杂度O(n+k);