Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
1 class Solution {
2 public:
3 vector<vector<int> > combine(int n, int k) {
4 vector<vector<int> > res;
5 vector<int> com;
6 combineRE(n, k, 1, com, res);
7 return res;
8 }
9
10 void combineRE(int n, int k, int start, vector<int> &com, vector<vector<int> > &res) {
11 int m = com.size();
12 if(m == k) {
13 res.push_back(com);
14 return;
15 }
16 for(int i = start; i <= n-k+1+m; i++) {
17 com.push_back(i);
18 combineRE(n, k, i+1, com, res);
19 com.pop_back();
20 }
21 }
22 };

浙公网安备 33010602011771号