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:

1
2
3
4
5
6
7
8
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

思路

利用回溯的方法来计算组合数。

我们知道组合数的k,我们就可以知道回溯的时候要走几层。知道组合数的n,我们可以知道组合数的总数目。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
void combination(int start, int n, int k, vector<int> cur, vector<vector<int>>& result){
if (k == 0){
result.push_back(cur);
}
else{
for (int i = start; i <= n; i++){
vector<int> tmp = cur;
tmp.push_back(i);
combination(i+1, n, k-1, tmp, result);
}
}
}
vector<vector<int>> combine(int n, int k) {
vector<int> cur;
vector<vector<int>> result;
combination(1, n, k, cur, result);
return result;
}
};