leetcode-77-combinations

题目

给定n,k,输出Cnk的所有组合数

分析

显然利用dfs进行遍历

C++代码实现

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:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp;
dfs(res, tmp, 1, k, n);
return res;
}


void (vector<vector<int>> &res, vector<int> tmp, int start, int k, int n){
if(tmp.size() == k) {
res.push_back(tmp);//与java不同,不需要新建vector对象。
return;
}
for(int i = start; i <= n; i++){
tmp.push_back(i);
combine_func(res,tmp, i + 1, k, n);
tmp.pop_back();
}
}
};