Backtrack的题目,没有什么好说的。时间复杂度O(C(n , k)),空间复杂度k,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int>> combine(int n, int k) { | |
if(k > n)return {}; | |
vector<vector<int>> res; | |
vector<int> curr; | |
backtrack(res, curr, 1, n, k); | |
return res; | |
} | |
private: | |
void backtrack(vector<vector<int>>& res, vector<int>& curr, int i, int n, int k) | |
{ | |
if(curr.size() == k) | |
{ | |
res.push_back(curr); | |
return; | |
} | |
for(int j = i; j <= n; ++j) | |
{ | |
curr.push_back(j); | |
backtrack(res, curr, j+ 1, n, k); | |
curr.pop_back(); | |
} | |
} | |
}; |
No comments:
Post a Comment