forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubsets.cpp
More file actions
30 lines (26 loc) · 693 Bytes
/
subsets.cpp
File metadata and controls
30 lines (26 loc) · 693 Bytes
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
// Time: O(n * 2^n)
// Space: O(1)
class Solution {
public:
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
vector<vector<int>> subsets(vector<int> &nums) {
const int size = nums.size();
const int set_size = 1 << size;
vector<vector<int>> ans;
vector<int> v;
sort(nums.begin(), nums.end());
for (int i = 0; i < set_size; ++i) {
for (int j = 0; j < size; ++j) {
if (i & (1 << j)) {
v.emplace_back(nums[j]);
}
}
ans.emplace_back(v);
v.clear();
}
return ans;
}
};