Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e7a6b6a

Browse files
#917 Power Set using Bitwise with C++
1 parent 1a45bee commit e7a6b6a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
We have to find all elements of power set of given set as string using bit manipulation
3+
4+
5+
Example 1:
6+
I/p : "sd"
7+
O/p : "", "s", "d", "sd"
8+
9+
Example 2:
10+
I/p : "abc"
11+
O/p : "", "a", "b", "c", "ab", "bc", "ac", "abc"
12+
13+
Formula for Power Set: 2^n , where n is number of elements present in set.
14+
15+
Here, we will be using the formula mentioned above
16+
in the function printPowerSet.
17+
In function printPowerSet Outer function has complexity of 2^n
18+
and inner funtion has complexity of n.
19+
So Time Complexity = Theta(2^n * n)
20+
21+
*/
22+
23+
#include<iostream>
24+
#include<bits/stdc++.h> // we can also use cmath but bits/stdc++.h is prefered more
25+
using namespace std;
26+
27+
int printPowerSet(string str) // function to print all elements of power set
28+
{
29+
int n = str.length();
30+
int pow_Size = pow(2, n);
31+
32+
for (int counter = 0; counter < pow_Size; counter++) // This for loop will run for 2^n times i.e. to find all elements for powerset
33+
{
34+
for (int j = 0; j < n; j++) // This will run for total n times to print elements where the bit is set.
35+
{
36+
if ((counter & (1 << j)) != 0) // Check every bit and if bit is set then prints the element of that index.
37+
{
38+
cout << str[j];
39+
}
40+
}
41+
cout << endl;
42+
}
43+
44+
}
45+
46+
int main()
47+
{
48+
string str = "abc"; // string to be passed
49+
50+
printPowerSet(str);
51+
52+
return 0;
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /