77. 组合
思路:回溯
实现
点击查看代码
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
backTracking(n, k, 1);
return result;
}
private:
vector<int> path;
vector<vector<int>> result;
void backTracking(const int& n, const int& k, int startIndex) {
if(path.size() == k){
result.push_back(path);
return;
}
for(int i = startIndex; i <= n - (k-path.size()) + 1; i++) {
path.push_back(i);
backTracking(n, k, i+1);
path.pop_back();
}
}
};
复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(n)