回溯:
// // Created by jt on 2020/9/24. // #include <vector> using namespace std; class Solution { public: /** * * @param n int整型 * @param k int整型 * @return int整型vector<vector<>> */ vector<vector<int> > combine(int n, int k) { // write code here vector<vector<int>> res; vector<int> vec; backtrack(res, vec, n, k); return res; } void backtrack(vector<vector<int>> &res, vector<int> &vec, int n, int k) { if (vec.size() == k) { res.push_back(vec); return; } int start = vec.empty() ? 1 : vec[vec.size() - 1] + 1; for (int i = start; i <= n; ++i) { vec.push_back(i); backtrack(res, vec, n, k); vec.pop_back(); } } };