题目:
注意下一个从path.back()+1开始这样避免像(1,2),(2,1)这样的重复
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <vector> using std::vector;
class Solution { private: vector<vector<int> > res; void backtrace(vector<int> &path, int n, int k) { if (path.size() == k) { res.push_back(path); return; } int start = path.empty() ? 1 : path.back() + 1; for (int i = start; i <= n; i++) { path.push_back(i);
backtrace(path, n, k); path.pop_back(); } } public: vector<vector<int> > combine(int n, int k) { res = vector<vector<int> >(); vector<int> path; backtrace(path, n, k); return res; } };
|