-
Notifications
You must be signed in to change notification settings - Fork 0
/
subsets.cpp
89 lines (81 loc) · 2.06 KB
/
subsets.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* =====================================================================================
*
* Filename: subsets.cpp
*
* Description: Subsets: Given a set of distinct integers, nums, return all possible
* subsets (the power set).
*
* Version: 1.0
* Created: 07/05/18 08:33:59
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Solution
{
public:
std::vector<std::vector<int> > subsets(const std::vector<int>& nums)
{
std::vector<std::vector<int> > sub_nums;
if (nums.size() == 0)
{
return sub_nums;
}
std::vector<int> tmp_nums;
dfs(nums, 0, &tmp_nums, &sub_nums);
return sub_nums;
}
private:
void dfs(const std::vector<int>& nums, int idx, std::vector<int>* tmp_nums, std::vector<std::vector<int> >* sub_nums)
{
if (idx == 0)
{
sub_nums->push_back(std::vector<int>{});
}
if (idx >= nums.size())
{
return;
}
dfs(nums, idx + 1, tmp_nums, sub_nums);
tmp_nums->push_back(nums[idx]);
dfs(nums, idx + 1, tmp_nums, sub_nums);
std::vector<int> new_nums(*tmp_nums);
sub_nums->push_back(new_nums);
tmp_nums->pop_back();
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {1, 2, 3};
if (argc > 2)
{
nums.clear();
for (int i = 1; i < argc; i++)
{
nums.push_back(atoi(argv[i]));
}
}
auto sub_nums = Solution().subsets(nums);
for (const auto& sub_arr: sub_nums)
{
printf("[");
for (size_t i = 0; i < sub_arr.size(); i++)
{
if (i != 0)
{
printf(", ");
}
printf("%d", sub_arr[i]);
}
printf("]\n");
}
return 0;
}