-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinations.cpp
More file actions
72 lines (67 loc) · 1.67 KB
/
combinations.cpp
File metadata and controls
72 lines (67 loc) · 1.67 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* =====================================================================================
*
* Filename: combinations.cpp
*
* Description: 77. Combinations. Given two integers n and k, return all possible
* combinations of k numbers out of 1 ... n.
*
* Version: 1.0
* Created: 03/27/19 03:31:54
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Solution
{
public:
std::vector<std::vector<int>> combine(int n, int k)
{
std::vector<std::vector<int>> combx;
std::vector<int> current;
combine(n, k, 1, ¤t, &combx);
return combx;
}
private:
void combine(int n, int k, int start, std::vector<int>* current, std::vector<std::vector<int>>* combx)
{
if (n < 1 || k < 1 || k > n)
{
return;
}
else if (current->size() == k)
{
combx->push_back(*current);
return;
}
for (int i = start; i <= n; i++)
{
current->push_back(i);
combine(n, k, i + 1, current, combx);
current->pop_back();
}
}
};
int main(int argc, char* argv[])
{
int n = 4;
int k = 2;
auto combx = Solution().combine(n, k);
printf("Size of combinations: %lu\n", combx.size());
for (const auto& item: combx)
{
for (auto num: item)
{
printf("%d ", num);
}
printf("\n");
}
return 0;
}