Skip to content

Commit 454f006

Browse files
committed
Add Subsets using Bit Manipulation
1 parent dce9bd9 commit 454f006

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/cpp/SubsetsBitManipulation.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/*
6+
Problem Statement:
7+
Given an integer array nums of unique elements, return all possible
8+
subsets (the power set).
9+
10+
The solution set must not contain duplicate subsets. Return the solution in any order.
11+
*/
12+
13+
// Using Bit Manipulation
14+
// 1) Traverse all subsets
15+
// 2) Traverse all elements of nums
16+
// 3) Check if jth bit is set in i
17+
// It is like for 3 elements:
18+
// 000, 001, 010, 011, 100, 101, 110, 111
19+
// where 1 means that element is present in the subset
20+
// Time: O(n * 2ⁿ)
21+
// Space: O(1)
22+
vector<vector<int>> subsets(vector<int> &nums)
23+
{
24+
int n = nums.size();
25+
int total = 1 << n; // 2ⁿ
26+
vector<vector<int>> ans(total);
27+
28+
// Traverse all subsets
29+
for (int i = 0; i < total; i++) // 2ⁿ
30+
{
31+
// Traverse elements of nums
32+
for (int j = 0; j < n; j++) // n
33+
{
34+
// Check if jth bit is set in i
35+
if ((1 << j) & i)
36+
{
37+
ans[i].push_back(nums[j]);
38+
}
39+
}
40+
}
41+
42+
return ans;
43+
}
44+
45+
int main()
46+
{
47+
vector<int> nums = {1, 2, 3};
48+
vector<vector<int>> ans = subsets(nums);
49+
50+
cout << "Subsets are: \n";
51+
for (auto v : ans)
52+
{
53+
cout << "[ ";
54+
for (auto i : v)
55+
{
56+
cout << i << " ";
57+
}
58+
cout << "]\n";
59+
}
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)