forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
57 lines (42 loc) · 1.04 KB
/
main3.cpp
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
/// Source : https://leetcode.com/problems/combinations/description/
/// Author : liuyubobobo
/// Time : 2019-03-29
#include <iostream>
#include <vector>
using namespace std;
/// Using bit mask
/// Time Complexity: O(2^n * n)
/// Space Complexity: O(1)
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
int LIMIT = (1 << n);
for(int i = 0; i < LIMIT; i ++){
vector<int> tres = get_vector(i);
if(tres.size() == k) res.push_back(tres);
}
return res;
}
private:
vector<int> get_vector(int num){
vector<int> res;
int i = 1;
while(num){
if(num % 2) res.push_back(i);
i ++, num /= 2;
}
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<vector<int>> res = Solution().combine(4,2);
for( int i = 0 ; i < res.size() ; i ++ )
print_vec(res[i]);
return 0;
}