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 111Value 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++
| // C++ program for the above approach #include <bits/stdc++.h> usingnamespacestd;  // Function to print all the power set voidprintPowerSet(char* set, intset_size) {     // Set_size of power set of a set with set_size     // n is (2^n-1)     unsigned intpow_set_size = pow(2, set_size);     intcounter, j;      // Run from counter 000..0 to 111..1     for(counter = 0; counter < pow_set_size; counter++) {         for(j = 0; j < set_size; j++) {             // Check if jth bit in the counter is set             // If set then print jth element from set             if(counter & (1 << j))                 cout << set[j];         }         cout << endl;     } }  /*Driver code*/intmain() {     charset[] = { 'a', 'b', 'c'};     printPowerSet(set, 3);     return0; }  // This code is contributed by SoM15242 | 
C
| #include <stdio.h> #include <math.h>  voidprintPowerSet(char*set, intset_size) {     /*set_size of power set of a set with set_size       n is (2**n -1)*/    unsigned intpow_set_size = pow(2, set_size);     intcounter, j;      /*Run from counter 000..0 to 111..1*/    for(counter = 0; counter < pow_set_size; counter++)     {       for(j = 0; j < set_size; j++)        {           /* Check if jth bit in the counter is set              If set then print jth element from set */          if(counter & (1<<j))             printf("%c", set[j]);        }        printf("\n");     } }  /*Driver program to test printPowerSet*/intmain() {     charset[] = {'a','b','c'};     printPowerSet(set, 3);     return0; }  | 
Java
| // Java program for power set importjava .io.*;  publicclassGFG {          staticvoidprintPowerSet(char[]set,                             intset_size)     {                  /*set_size of power set of a set         with set_size n is (2**n -1)*/        longpow_set_size =              (long)Math.pow(2, set_size);         intcounter, j;              /*Run from counter 000..0 to         111..1*/        for(counter = 0; counter <                  pow_set_size; counter++)         {             for(j = 0; j < set_size; j++)             {                 /* Check if jth bit in the                  counter is set If set then                  print jth element from set */                if((counter & (1<< j)) > 0)                     System.out.print(set[j]);             }                          System.out.println();         }     }          // Driver program to test printPowerSet     publicstaticvoidmain (String[] args)     {         char[]set = {'a', 'b', 'c'};         printPowerSet(set, 3);     } }  // This code is contributed by anuj_67.  | 
Python3
| # python3 program for power set  importmath;  defprintPowerSet(set,set_size):          # set_size of power set of a set     # with set_size n is (2**n -1)     pow_set_size =(int) (math.pow(2, set_size));     counter =0;     j =0;          # Run from counter 000..0 to 111..1     forcounter inrange(0, pow_set_size):         forj inrange(0, set_size):                          # Check if jth bit in the              # counter is set If set then              # print jth element from set              if((counter & (1<< j)) > 0):                 print(set[j], end ="");         print("");  # Driver program to test printPowerSet set=['a', 'b', 'c']; printPowerSet(set, 3);  # This code is contributed by mits.  | 
C#
| // C# program for power set usingSystem;  classGFG {          staticvoidprintPowerSet(char[]set,                             intset_size)     {         /*set_size of power set of a set         with set_size n is (2**n -1)*/        uintpow_set_size =                (uint)Math.Pow(2, set_size);         intcounter, j;              /*Run from counter 000..0 to         111..1*/        for(counter = 0; counter <                     pow_set_size; counter++)         {             for(j = 0; j < set_size; j++)             {                 /* Check if jth bit in the                  counter is set If set then                  print jth element from set */                if((counter & (1 << j)) > 0)                     Console.Write(set[j]);             }                          Console.WriteLine();         }     }          // Driver program to test printPowerSet     publicstaticvoidMain ()     {         char[]set= {'a', 'b', 'c'};         printPowerSet(set, 3);     } }  // This code is contributed by anuj_67.  | 
Javascript
| <script> // javascript program for power setpublic       functionprintPowerSet(set, set_size)      {          /*          * set_size of power set of a set with set_size n is (2**n -1)          */        varpow_set_size = parseInt(Math.pow(2, set_size));         varcounter, j;          /*          * Run from counter 000..0 to 111..1          */        for(counter = 0; counter < pow_set_size; counter++)         {             for(j = 0; j < set_size; j++)              {                              /*                  * Check if jth bit in the counter is set If set then print jth element from set                  */                if((counter & (1 << j)) > 0)                     document.write(set[j]);             }             document.write("<br/>");         }     }      // Driver program to test printPowerSet         let set = [ 'a', 'b', 'c'];         printPowerSet(set, 3);  // This code is contributed by shikhasingrajput  </script>  | 
PHP
| <?php // PHP program for power set  functionprintPowerSet($set, $set_size) {      // set_size of power set of     // a set with set_size     // n is (2**n -1)     $pow_set_size= pow(2, $set_size);     $counter; $j;      // Run from counter 000..0 to     // 111..1     for($counter= 0; $counter< $pow_set_size;                                     $counter++)     {         for($j= 0; $j< $set_size; $j++)         {                          /* Check if jth bit in                 the counter is set                If set then print                 jth element from set */            if($counter& (1 << $j))                 echo$set[$j];         }              echo"\n";     } }      // Driver Code     $set= array('a','b','c');     printPowerSet($set, 3);  // This code is contributed by Vishal Tripathi ?>  | 
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++
| // C++ program for the above approach #include <bits/stdc++.h> usingnamespacestd;  // Function to print all the power set voidprintPowerSet(charset[], intn) {     bool*contain = newbool[n]{0};          // Empty subset     cout << ""<< endl;     for(inti = 0; i < n; i++)     {         contain[i] = 1;         // All permutation         do        {             for(intj = 0; j < n; j++)                 if(contain[j])                     cout << set[j];             cout << endl;         } while(prev_permutation(contain, contain + n));     } }  /*Driver code*/intmain() {     charset[] = {'a','b','c'};     printPowerSet(set, 3);     return0; }  // This code is contributed by zlatkodamijanic | 
Java
| // Java program for the above approach  importjava.util.*;  classGFG {    // A function to reverse only the indices in the   // range [l, r]   staticint[] reverse(int[] arr, intl, intr)   {     intd = (r - l + 1) / 2;     for(inti = 0; i < d; i++) {       intt = arr[l + i];       arr[l + i] = arr[r - i];       arr[r - i] = t;     }     returnarr;   }   // A function which gives previous   // permutation of the array   // and returns true if a permutation   // exists.   staticbooleanprev_permutation(int[] str)   {     // Find index of the last     // element of the string     intn = str.length - 1;      // Find largest index i such     // that str[i - 1] > str[i]     inti = n;     while(i > 0&& str[i - 1] <= str[i]) {       i--;     }      // If string is sorted in     // ascending order we're     // at the last permutation     if(i <= 0) {       returnfalse;     }      // Note - str[i..n] is sorted     // in ascending order Find     // rightmost element's index     // that is less than str[i - 1]     intj = i - 1;     while(j + 1<= n && str[j + 1] < str[i - 1]) {       j++;     }      // Swap character at i-1 with j     inttemper = str[i - 1];     str[i - 1] = str[j];     str[j] = temper;      // Reverse the substring [i..n]     str = reverse(str, i, str.length - 1);      returntrue;   }    // Function to print all the power set   staticvoidprintPowerSet(char[] set, intn)   {      int[] contain = newint[n];     for(inti = 0; i < n; i++)       contain[i] = 0;      // Empty subset     System.out.println();     for(inti = 0; i < n; i++) {       contain[i] = 1;        // To avoid changing original 'contain'       // array creating a copy of it i.e.       // "Contain"       int[] Contain = newint[n];       for(intindx = 0; indx < n; indx++) {         Contain[indx] = contain[indx];       }        // All permutation       do{         for(intj = 0; j < n; j++) {           if(Contain[j] != 0) {             System.out.print(set[j]);           }         }         System.out.print("\n");        } while(prev_permutation(Contain));     }   }    /*Driver code*/  publicstaticvoidmain(String[] args)   {     char[] set = { 'a', 'b', 'c'};     printPowerSet(set, 3);   } }  // This code is contributed by phasing17 | 
Python3
| # Python3 program for the above approach  # A function which gives previous # permutation of the array # and returns true if a permutation # exists. defprev_permutation(str):      # Find index of the last     # element of the string     n =len(str) -1     # Find largest index i such     # that str[i - 1] > str[i]     i =n     while(i > 0andstr[i -1] <=str[i]):         i -=1     # If string is sorted in     # ascending order we're     # at the last permutation     if(i <=0):         returnFalse     # Note - str[i..n] is sorted     # in ascending order Find     # rightmost element's index     # that is less than str[i - 1]     j =i -1    while(j +1<=n andstr[j +1] < str[i -1]):         j +=1     # Swap character at i-1 with j     temper =str[i -1]     str[i -1] =str[j]     str[j] =temper      # Reverse the substring [i..n]     size =n-i+1    foridx inrange(int(size /2)):         temp =str[idx +i]         str[idx +i] =str[n -idx]         str[n -idx] =temp      returnTrue # Function to print all the power set defprintPowerSet(set, n):      contain =[0for_ inrange(n)]      # Empty subset     print()      fori inrange(n):         contain[i] =1         # To avoid changing original 'contain'         # array creating a copy of it i.e.         # "Contain"         Contain =contain.copy()          # All permutation         whileTrue:             forj inrange(n):                 if(Contain[j]):                     print(set[j], end="")             print()             ifnotprev_permutation(Contain):                 break # Driver code set=['a', 'b', 'c'] printPowerSet(set, 3)  # This code is contributed by phasing17  | 
C#
| // C# program for the above approach  usingSystem; usingSystem.Linq; usingSystem.Collections.Generic;  classGFG {    // A function which gives previous   // permutation of the array   // and returns true if a permutation   // exists.   staticboolprev_permutation(int[] str)   {     // Find index of the last     // element of the string     intn = str.Length - 1;      // Find largest index i such     // that str[i - 1] > str[i]     inti = n;     while(i > 0 && str[i - 1] <= str[i]) {       i--;     }      // If string is sorted in     // ascending order we're     // at the last permutation     if(i <= 0) {       returnfalse;     }      // Note - str[i..n] is sorted     // in ascending order Find     // rightmost element's index     // that is less than str[i - 1]     intj = i - 1;     while(j + 1 <= n && str[j + 1] < str[i - 1]) {       j++;     }      // Swap character at i-1 with j     vartemper = str[i - 1];     str[i - 1] = str[j];     str[j] = temper;      // Reverse the substring [i..n]     intsize = n - i + 1;     Array.Reverse(str, i, size);      returntrue;   }    // Function to print all the power set   staticvoidprintPowerSet(char[] set, intn)   {      int[] contain = newint[n];     for(inti = 0; i < n; i++)       contain[i] = 0;      // Empty subset     Console.WriteLine();     for(inti = 0; i < n; i++) {       contain[i] = 1;        // To avoid changing original 'contain'       // array creating a copy of it i.e.       // "Contain"       int[] Contain = newint[n];       for(intindx = 0; indx < n; indx++) {         Contain[indx] = contain[indx];       }        // All permutation       do{         for(intj = 0; j < n; j++) {           if(Contain[j] != 0) {             Console.Write(set[j]);           }         }         Console.Write("\n");        } while(prev_permutation(Contain));     }   }    /*Driver code*/  publicstaticvoidMain(string[] args)   {     char[] set= { 'a', 'b', 'c'};     printPowerSet(set, 3);   } }  // This code is contributed by phasing17 | 
Javascript
| // JavaScript program for the above approach  // A function which gives previous  // permutation of the array // and returns true if a permutation  // exists.  functionprev_permutation(str){         // Find index of the last     // element of the string     let n = str.length - 1;       // Find largest index i such     // that str[i - 1] > str[i]     let i = n;     while(i > 0 && str[i - 1] <= str[i]){         i--;     }               // If string is sorted in     // ascending order we're     // at the last permutation     if(i <= 0){         returnfalse;     }       // Note - str[i..n] is sorted     // in ascending order Find     // rightmost element's index     // that is less than str[i - 1]     let j = i - 1;     while(j + 1 <= n && str[j + 1] < str[i - 1]){         j++;     }          // Swap character at i-1 with j     const temper = str[i - 1];     str[i - 1] = str[j];     str[j] = temper;          // Reverse the substring [i..n]     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;     }          returntrue; }  // Function to print all the power set functionprintPowerSet(set, n){         let contain = newArray(n).fill(0);      // Empty subset     document.write("<br>");     for(let i = 0; i < n; i++){         contain[i] = 1;                   // To avoid changing original 'contain'          // array creating a copy of it i.e.         // "Contain"         let Contain = newArray(n);         for(let indx = 0; indx < n; indx++){             Contain[indx] = contain[indx];         }          // All permutation         do{             for(let j = 0; j < n; j++){                                 if(Contain[j]){                     document.write(set[j]);                 }               }             document.write("<br>");                      } while(prev_permutation(Contain));     } }  /*Driver code*/const set = ['a','b','c']; printPowerSet(set, 3);  // This code is contributed by Gautam goel (gautamgoel962) | 
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> usingnamespacestd;  voidfindPowerSet(char* s, vector<char> &res, intn){         if(n == 0) {             for(autoi: 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);     }      voidprintPowerSet(char* s, intn){     vector<char> ans;     findPowerSet(s, ans, n); }   intmain() {     charset[] = { 'a', 'b', 'c'};     printPowerSet(set, 3);     return0; } | 
Java
| importjava.util.*;   classMain {     publicstaticvoidfindPowerSet(char[]s, Deque<Character> res,intn){         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);     }       publicstaticvoidmain(String[] args)     {         char[]set = {'a', 'b', 'c'};         Deque<Character> res = newArrayDeque<>();         findPowerSet(set, res, 3);     } }  | 
Python3
| # Python3 program to implement the approach  # Function to build the power sets deffindPowerSet(s, res, n):     if(n ==0):         fori inres:             print(i, end="")         print()         return     # append the subset to result     res.append(s[n -1])     findPowerSet(s, res, n -1)     res.pop()     findPowerSet(s, res, n -1)  # Function to print the power set defprintPowerSet(s, n):     ans =[]     findPowerSet(s, ans, n)  # Driver code set=['a', 'b', 'c'] printPowerSet(set, 3)  # This code is contributed by phasing17  | 
C#
| // C# code to implement the approach  usingSystem; usingSystem.Collections.Generic;  classGFG  {     // function to build the power set     publicstaticvoidfindPowerSet(char[] s,                                     List<char> res, intn)     {          // if the end is reached         // display all elements of res         if(n == 0) {             foreach(varelement inres)                 Console.Write(element);             Console.WriteLine();             return;         }          // append the subset to res         res.Add(s[n - 1]);         findPowerSet(s, res, n - 1);         res.RemoveAt(res.Count - 1);         findPowerSet(s, res, n - 1);     }      // Driver code     publicstaticvoidMain(string[] args)     {         char[] set= { 'a', 'b', 'c'};         List<char> res = newList<char>();          // Function call         findPowerSet(set, res, 3);     } }  // This code is contributed by phasing17 | 
Javascript
| // JavaScript program to implement the approach  // Function to build the power sets functionfindPowerSet(s, res, n) {     if(n == 0)     {         for(vari of res)             process.stdout.write(i + "");         process.stdout.write("\n");         return;     }      // append the subset to result     res.push(s[n - 1]);     findPowerSet(s, res, n - 1);     res.pop();     findPowerSet(s, res, n - 1); }  // Function to print the power set functionprintPowerSet(s, n) {     let ans = [];     findPowerSet(s, ans, n); }   // Driver code let set = ['a', 'b', 'c']; printPowerSet(set, 3);   // This code is contributed by phasing17  | 
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
 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







