Leetcode 77. Combinations

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Combinations

2. Solution

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

Reference

  1. https://leetcode.com/problems/combinations/description/
如果有收获,可以请我喝杯咖啡!