Power Set
Last Updated :
08 Mar, 2024
Power Set: Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.
If S has n elements in it then P(s) will have 2n elements
Example:
Set = [a,b,c]
power_set_size = pow(2, 3) = 8
Run for binary counter = 000 to 111
Value of Counter Subset
000 -> Empty set
001 -> a
010 -> b
011 -> ab
100 -> c
101 -> ac
110 -> bc
111 -> abc
Algorithm:
Input: Set[], set_size
1. Get the size of power set
powet_set_size = pow(2, set_size)
2 Loop for counter from 0 to pow_set_size
(a) Loop for i = 0 to set_size
(i) If ith bit in counter is set
Print ith element from set for this subset
(b) Print separator for subsets i.e., newline
Method 1:
For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set.
For example, for the set S {x, y, z}, generate all binary numbers from 0 to 23-1 and for each generated number, the corresponding set can be found by considering set bits in the number.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void printPowerSet( char * set, int set_size)
{
unsigned int pow_set_size = pow (2, set_size);
int counter, j;
for (counter = 0; counter < pow_set_size; counter++) {
for (j = 0; j < set_size; j++) {
if (counter & (1 << j))
cout << set[j];
}
cout << endl;
}
}
int main()
{
char set[] = { 'a' , 'b' , 'c' };
printPowerSet(set, 3);
return 0;
}
|
C
#include <stdio.h>
#include <math.h>
void printPowerSet( char *set, int set_size)
{
unsigned int pow_set_size = pow (2, set_size);
int counter, j;
for (counter = 0; counter < pow_set_size; counter++)
{
for (j = 0; j < set_size; j++)
{
if (counter & (1<<j))
printf ( "%c" , set[j]);
}
printf ( "\n" );
}
}
int main()
{
char set[] = { 'a' , 'b' , 'c' };
printPowerSet(set, 3);
return 0;
}
|
Java
import java .io.*;
public class GFG {
static void printPowerSet( char []set,
int set_size)
{
long pow_set_size =
( long )Math.pow( 2 , set_size);
int counter, j;
for (counter = 0 ; counter <
pow_set_size; counter++)
{
for (j = 0 ; j < set_size; j++)
{
if ((counter & ( 1 << j)) > 0 )
System.out.print(set[j]);
}
System.out.println();
}
}
public static void main (String[] args)
{
char []set = { 'a' , 'b' , 'c' };
printPowerSet(set, 3 );
}
}
|
Python3
import math;
def printPowerSet( set ,set_size):
pow_set_size = ( int ) (math. pow ( 2 , set_size));
counter = 0 ;
j = 0 ;
for counter in range ( 0 , pow_set_size):
for j in range ( 0 , set_size):
if ((counter & ( 1 << j)) > 0 ):
print ( set [j], end = "");
print ("");
set = [ 'a' , 'b' , 'c' ];
printPowerSet( set , 3 );
|
C#
using System;
class GFG {
static void printPowerSet( char [] set ,
int set_size)
{
uint pow_set_size =
( uint )Math.Pow(2, set_size);
int counter, j;
for (counter = 0; counter <
pow_set_size; counter++)
{
for (j = 0; j < set_size; j++)
{
if ((counter & (1 << j)) > 0)
Console.Write( set [j]);
}
Console.WriteLine();
}
}
public static void Main ()
{
char [] set = { 'a' , 'b' , 'c' };
printPowerSet( set , 3);
}
}
|
Javascript
<script>
function printPowerSet(set, set_size)
{
var pow_set_size = parseInt(Math.pow(2, set_size));
var counter, j;
for (counter = 0; counter < pow_set_size; counter++)
{
for (j = 0; j < set_size; j++)
{
if ((counter & (1 << j)) > 0)
document.write(set[j]);
}
document.write( "<br/>" );
}
}
let set = [ 'a' , 'b' , 'c' ];
printPowerSet(set, 3);
</script>
|
PHP
<?php
function printPowerSet( $set , $set_size )
{
$pow_set_size = pow(2, $set_size );
$counter ; $j ;
for ( $counter = 0; $counter < $pow_set_size ;
$counter ++)
{
for ( $j = 0; $j < $set_size ; $j ++)
{
if ( $counter & (1 << $j ))
echo $set [ $j ];
}
echo "\n" ;
}
}
$set = array ( 'a' , 'b' , 'c' );
printPowerSet( $set , 3);
?>
|
Output
a
b
ab
c
ac
bc
abc
Time Complexity: O(n2n)
Auxiliary Space: O(1)
Method 2: (sorted by cardinality)
In auxiliary array of bool set all elements to 0. That represent an empty set. Set first element of auxiliary array to 1 and generate all permutations to produce all subsets with one element. Then set the second element to 1 which will produce all subsets with two elements, repeat until all elements are included.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void printPowerSet( char set[], int n)
{
bool *contain = new bool [n]{0};
cout << "" << endl;
for ( int i = 0; i < n; i++)
{
contain[i] = 1;
do
{
for ( int j = 0; j < n; j++)
if (contain[j])
cout << set[j];
cout << endl;
} while (prev_permutation(contain, contain + n));
}
}
int main()
{
char set[] = { 'a' , 'b' , 'c' };
printPowerSet(set, 3);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int [] reverse( int [] arr, int l, int r)
{
int d = (r - l + 1 ) / 2 ;
for ( int i = 0 ; i < d; i++) {
int t = arr[l + i];
arr[l + i] = arr[r - i];
arr[r - i] = t;
}
return arr;
}
static boolean prev_permutation( int [] str)
{
int n = str.length - 1 ;
int i = n;
while (i > 0 && str[i - 1 ] <= str[i]) {
i--;
}
if (i <= 0 ) {
return false ;
}
int j = i - 1 ;
while (j + 1 <= n && str[j + 1 ] < str[i - 1 ]) {
j++;
}
int temper = str[i - 1 ];
str[i - 1 ] = str[j];
str[j] = temper;
str = reverse(str, i, str.length - 1 );
return true ;
}
static void printPowerSet( char [] set, int n)
{
int [] contain = new int [n];
for ( int i = 0 ; i < n; i++)
contain[i] = 0 ;
System.out.println();
for ( int i = 0 ; i < n; i++) {
contain[i] = 1 ;
int [] Contain = new int [n];
for ( int indx = 0 ; indx < n; indx++) {
Contain[indx] = contain[indx];
}
do {
for ( int j = 0 ; j < n; j++) {
if (Contain[j] != 0 ) {
System.out.print(set[j]);
}
}
System.out.print( "\n" );
} while (prev_permutation(Contain));
}
}
public static void main(String[] args)
{
char [] set = { 'a' , 'b' , 'c' };
printPowerSet(set, 3 );
}
}
|
Python3
def prev_permutation( str ):
n = len ( str ) - 1
i = n
while (i > 0 and str [i - 1 ] < = str [i]):
i - = 1
if (i < = 0 ):
return False
j = i - 1
while (j + 1 < = n and str [j + 1 ] < str [i - 1 ]):
j + = 1
temper = str [i - 1 ]
str [i - 1 ] = str [j]
str [j] = temper
size = n - i + 1
for idx in range ( int (size / 2 )):
temp = str [idx + i]
str [idx + i] = str [n - idx]
str [n - idx] = temp
return True
def printPowerSet( set , n):
contain = [ 0 for _ in range (n)]
print ()
for i in range (n):
contain[i] = 1
Contain = contain.copy()
while True :
for j in range (n):
if (Contain[j]):
print ( set [j], end = "")
print ()
if not prev_permutation(Contain):
break
set = [ 'a' , 'b' , 'c' ]
printPowerSet( set , 3 )
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static bool prev_permutation( int [] str)
{
int n = str.Length - 1;
int i = n;
while (i > 0 && str[i - 1] <= str[i]) {
i--;
}
if (i <= 0) {
return false ;
}
int j = i - 1;
while (j + 1 <= n && str[j + 1] < str[i - 1]) {
j++;
}
var temper = str[i - 1];
str[i - 1] = str[j];
str[j] = temper;
int size = n - i + 1;
Array.Reverse(str, i, size);
return true ;
}
static void printPowerSet( char [] set , int n)
{
int [] contain = new int [n];
for ( int i = 0; i < n; i++)
contain[i] = 0;
Console.WriteLine();
for ( int i = 0; i < n; i++) {
contain[i] = 1;
int [] Contain = new int [n];
for ( int indx = 0; indx < n; indx++) {
Contain[indx] = contain[indx];
}
do {
for ( int j = 0; j < n; j++) {
if (Contain[j] != 0) {
Console.Write( set [j]);
}
}
Console.Write( "\n" );
} while (prev_permutation(Contain));
}
}
public static void Main( string [] args)
{
char [] set = { 'a' , 'b' , 'c' };
printPowerSet( set , 3);
}
}
|
Javascript
function prev_permutation(str){
let n = str.length - 1;
let i = n;
while (i > 0 && str[i - 1] <= str[i]){
i--;
}
if (i <= 0){
return false ;
}
let j = i - 1;
while (j + 1 <= n && str[j + 1] < str[i - 1]){
j++;
}
const temper = str[i - 1];
str[i - 1] = str[j];
str[j] = temper;
let size = n-i+1;
for (let idx = 0; idx < Math.floor(size / 2); idx++) {
let temp = str[idx + i];
str[idx + i] = str[n - idx];
str[n - idx] = temp;
}
return true ;
}
function printPowerSet(set, n){
let contain = new Array(n).fill(0);
document.write( "<br>" );
for (let i = 0; i < n; i++){
contain[i] = 1;
let Contain = new Array(n);
for (let indx = 0; indx < n; indx++){
Contain[indx] = contain[indx];
}
do {
for (let j = 0; j < n; j++){
if (Contain[j]){
document.write(set[j]);
}
}
document.write( "<br>" );
} while (prev_permutation(Contain));
}
}
const set = [ 'a' , 'b' , 'c' ];
printPowerSet(set, 3);
|
Output
a
b
c
ab
ac
bc
abc
Time Complexity: O(n2n)
Auxiliary Space: O(n)
Method 3:
We can use backtrack here, we have two choices first consider that element then don’t consider that element.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void findPowerSet( char * s, vector< char > &res, int n){
if (n == 0) {
for ( auto i: res)
cout << i;
cout << "\n" ;
return ;
}
res.push_back(s[n - 1]);
findPowerSet(s, res, n - 1);
res.pop_back();
findPowerSet(s, res, n - 1);
}
void printPowerSet( char * s, int n){
vector< char > ans;
findPowerSet(s, ans, n);
}
int main()
{
char set[] = { 'a' , 'b' , 'c' };
printPowerSet(set, 3);
return 0;
}
|
Java
import java.util.*;
class Main
{
public static void findPowerSet( char []s, Deque<Character> res, int n){
if (n == 0 ){
for (Character element : res)
System.out.print(element);
System.out.println();
return ;
}
res.addLast(s[n - 1 ]);
findPowerSet(s, res, n - 1 );
res.removeLast();
findPowerSet(s, res, n - 1 );
}
public static void main(String[] args)
{
char []set = { 'a' , 'b' , 'c' };
Deque<Character> res = new ArrayDeque<>();
findPowerSet(set, res, 3 );
}
}
|
Python3
def findPowerSet(s, res, n):
if (n = = 0 ):
for i in res:
print (i, end = "")
print ()
return
res.append(s[n - 1 ])
findPowerSet(s, res, n - 1 )
res.pop()
findPowerSet(s, res, n - 1 )
def printPowerSet(s, n):
ans = []
findPowerSet(s, ans, n)
set = [ 'a' , 'b' , 'c' ]
printPowerSet( set , 3 )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void findPowerSet( char [] s,
List< char > res, int n)
{
if (n == 0) {
foreach ( var element in res)
Console.Write(element);
Console.WriteLine();
return ;
}
res.Add(s[n - 1]);
findPowerSet(s, res, n - 1);
res.RemoveAt(res.Count - 1);
findPowerSet(s, res, n - 1);
}
public static void Main( string [] args)
{
char [] set = { 'a' , 'b' , 'c' };
List< char > res = new List< char >();
findPowerSet( set , res, 3);
}
}
|
Javascript
function findPowerSet(s, res, n)
{
if (n == 0)
{
for ( var i of res)
process.stdout.write(i + "" );
process.stdout.write( "\n" );
return ;
}
res.push(s[n - 1]);
findPowerSet(s, res, n - 1);
res.pop();
findPowerSet(s, res, n - 1);
}
function printPowerSet(s, n)
{
let ans = [];
findPowerSet(s, ans, n);
}
let set = [ 'a' , 'b' , 'c' ];
printPowerSet(set, 3);
|
Output
cba
cb
ca
c
ba
b
a
Time Complexity: O(2^n)
Auxiliary Space: O(n)
Recursive program to generate power set
Refer Power Set in Java for implementation in Java and more methods to print power set.
References:
http://en.wikipedia.org/wiki/Power_set
If you like GeeksforGeeks and would like to contribute, you can also write an article using
write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Share your thoughts in the comments
Please Login to comment...