-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathGenerateSubsets.cpp
38 lines (31 loc) · 1.06 KB
/
GenerateSubsets.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
// Problem: https://leetcode.com/problems/subsets/
#include <vector>
using namespace std;
class GenerateSubsets {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<bool> taken;
taken.resize(nums.size(), false);
vector<vector<int>> result;
result.push_back({});
generate(nums, taken, result, 0);
return result;
}
void generate(const vector<int>& nums, vector<bool>& taken, vector<vector<int>>& result, int index) {
if (index == nums.size()) {
vector<int> r;
generateResult(nums, taken, r);
if (not r.empty()) result.push_back(r);
return;
}
taken[index] = true;
generate(nums, taken, result, index + 1);
taken[index] = false;
generate(nums, taken, result, index + 1);
}
void generateResult(const vector<int>& nums, const vector<bool>& taken, vector<int>& result) {
for (int index = 0; index < nums.size(); ++index) {
if (taken[index]) result.push_back(nums[index]);
}
}
};