Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order.
Examples:
Input : set = “abc”
Output : { “”, “a”, “b”, “c”, “ab”, “ac”, “bc”, “abc”}
Input : set = “abcd”
Output : { “”, “a” ,”ab” ,”abc” ,”abcd”, “abd” ,”ac” ,”acd”, “ad” ,”b”, “bc” ,”bcd” ,”bd” ,”c” ,”cd” ,”d” }
Recursive program to generate power set using Backtracking:
The idea is to fix a prefix, and generate all subsets beginning with the current prefix. After all subsets with a prefix are generated, replace the last character with one of the remaining characters.
Follow the approach to implement the above idea:
- The base condition of the recursive approach is when the current index reaches the size of the given string (i.e, index == n), then return
- First, print the current subset
- Iterate over the given string from the current index (i.e, index) to less than the size of the string
- Appending the remaining characters to the current subset
- Make the recursive call for the next index.
- Once all subsets beginning with the initial “curr” are printed, remove the last character to consider a different prefix of subsets.
Follow the steps below to implement the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void powerSet(string str, int index = -1, string curr = "" )
{
int n = str.length();
if (index == n)
return ;
cout << curr << "\n" ;
for ( int i = index + 1; i < n; i++) {
curr += str[i];
powerSet(str, i, curr);
curr.erase(curr.size() - 1);
}
return ;
}
int main()
{
string str = "abc" ;
powerSet(str);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void powerSet(String str, int index, String curr)
{
int n = str.length();
if (index == n) {
return ;
}
System.out.println(curr);
for ( int i = index + 1 ; i < n; i++) {
curr += str.charAt(i);
powerSet(str, i, curr);
curr = curr.substring( 0 , curr.length() - 1 );
}
}
public static void main(String[] args)
{
String str = "abc" ;
int index = - 1 ;
String curr = "" ;
powerSet(str, index, curr);
}
}
|
Python3
def powerSet(str1, index, curr):
n = len (str1)
if (index = = n):
return
print (curr)
for i in range (index + 1 , n):
curr + = str1[i]
powerSet(str1, i, curr)
curr = curr.replace(curr[ len (curr) - 1 ], "")
return
if __name__ = = '__main__' :
str = "abc"
powerSet( str , - 1 , "")
|
C#
using System;
class GFG {
static void powerSet( string str, int index, string curr)
{
int n = str.Length;
if (index == n) {
return ;
}
Console.WriteLine(curr);
for ( int i = index + 1; i < n; i++) {
curr += str[i];
powerSet(str, i, curr);
curr = curr.Substring(0, curr.Length - 1);
}
}
public static void Main()
{
string str = "abc" ;
int index = -1;
string curr = "" ;
powerSet(str, index, curr);
}
}
|
Javascript
<script>
function powerSet(str,index,curr)
{
let n = str.length;
if (index == n)
{
return ;
}
document.write(curr+ "<br>" );
for (let i = index + 1; i < n; i++)
{
curr += str[i];
powerSet(str, i, curr);
curr = curr.substring(0, curr.length - 1);
}
}
let str = "abc" ;
let index = -1;
let curr = "" ;
powerSet(str, index, curr);
</script>
|
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
Recursive program to generate power set using Recursion:
The idea is to consider two cases for every character.
(i) Consider current character as part of current subset
(ii) Do not consider current character as part of the current subset.
Follow the approach to implement the above idea:
- The base condition of the recursive approach is when the current index reaches the size of the given string (i.e, index == n). then print the current string say, curr.
- Make two recursive calls for the two cases for every character
- We consider the character as part of the current subset
- We do not consider current character as part of the current subset
Follow the steps below to implement the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void powerSet(string str, int index = 0, string curr = "" )
{
int n = str.length();
if (index == n) {
cout << curr << endl;
return ;
}
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
int main()
{
string str = "abc" ;
powerSet(str);
return 0;
}
|
Java
class GFG {
static void powerSet(String str, int index, String curr)
{
int n = str.length();
if (index == n) {
System.out.println(curr);
return ;
}
powerSet(str, index + 1 , curr + str.charAt(index));
powerSet(str, index + 1 , curr);
}
public static void main(String[] args)
{
String str = "abc" ;
int index = 0 ;
String curr = "" ;
powerSet(str, index, curr);
}
}
|
Python3
def powerSet(string, index, curr):
if index = = len (string):
print (curr)
return
powerSet(string, index + 1 ,
curr + string[index])
powerSet(string, index + 1 , curr)
if __name__ = = "__main__" :
s1 = "abc"
index = 0
curr = ""
powerSet(s1, index, curr)
|
C#
using System;
class GFG {
static void powerSet(String str, int index, String curr)
{
int n = str.Length;
if (index == n) {
Console.WriteLine(curr);
return ;
}
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
public static void Main()
{
String str = "abc" ;
int index = 0;
String curr = "" ;
powerSet(str, index, curr);
}
}
|
Javascript
<script>
function powerSet(str,index,curr)
{
let n = str.length;
if (index == n)
{
document.write(curr+ "<br>" );
return ;
}
powerSet(str, index + 1, curr + str[index]);
powerSet(str, index + 1, curr);
}
let str = "abc" ;
let index = 0;
let curr= "" ;
powerSet(str,index,curr);
</script>
|
Time Complexity: O(2n)
Auxiliary Space: O(n), For recursive call stack
Recursive program to generate power set using Backtracking using Bottom Up Approach:
The idea is to pick each element one by one from the input set, then generate a subset for the same, and we follow this process recursively.
Follow the steps below to implement the above idea:
- The base condition for the recursive call, when the current index becomes negative then add empty list into the allSubsets.
- Make recursive call for the current index – 1, then we’ll receive allSubsets list from 0 to index -1
- Create a list of list moreSubsets
- Iterate over all the subsets that are received from above recursive call
- Copy all the subset into newSubset
- Add the current item into newSubset
- Add newSubset into moreSubsets
- Add moreSubsets into allSubsets
- Finally, return allSubsets.
Follow the steps below to implement the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector<string> > getSubset(vector<string> set,
int index)
{
vector<vector<string> > allSubsets;
if (index < 0) {
vector<string> v;
allSubsets.push_back(v);
}
else {
allSubsets = getSubset(set, index - 1);
string item = set[index];
vector<vector<string> > moreSubsets;
for (vector<string> subset : allSubsets) {
vector<string> newSubset;
for ( auto it : subset)
newSubset.push_back(it);
newSubset.push_back(item);
moreSubsets.push_back(newSubset);
}
for ( auto it : moreSubsets)
allSubsets.push_back(it);
}
return allSubsets;
}
int main()
{
vector<string> set = { "a" , "b" , "c" };
int index = set.size() - 1;
vector<vector<string> > result = getSubset(set, index);
for ( auto it : result) {
cout << " [ " ;
for ( auto itr : it) {
cout << itr << "," ;
}
cout << "]," ;
}
}
|
Java
import java.util.ArrayList;
public class PowerSet {
public static void main(String[] args)
{
String[] set = { "a" , "b" , "c" };
int index = set.length - 1 ;
ArrayList<ArrayList<String> > result
= getSubset(set, index);
System.out.println(result);
}
static ArrayList<ArrayList<String> >
getSubset(String[] set, int index)
{
ArrayList<ArrayList<String> > allSubsets;
if (index < 0 ) {
allSubsets
= new ArrayList<ArrayList<String> >();
allSubsets.add( new ArrayList<String>());
}
else {
allSubsets = getSubset(set, index - 1 );
String item = set[index];
ArrayList<ArrayList<String> > moreSubsets
= new ArrayList<ArrayList<String> >();
for (ArrayList<String> subset : allSubsets) {
ArrayList<String> newSubset
= new ArrayList<String>();
newSubset.addAll(subset);
newSubset.add(item);
moreSubsets.add(newSubset);
}
allSubsets.addAll(moreSubsets);
}
return allSubsets;
}
}
|
Python3
def get_subset(s, index):
all_subsets = []
if index < 0 :
all_subsets.append([])
else :
all_subsets = get_subset(s, index - 1 )
item = s[index]
more_subsets = []
for subset in all_subsets:
new_subset = []
for i in subset:
new_subset.append(i)
new_subset.append(item)
more_subsets.append(new_subset)
for i in more_subsets:
all_subsets.append(i)
return all_subsets
set = [ "a" , "b" , "c" ]
index = len ( set ) - 1
result = get_subset( set , index)
for subset in result:
print ( "[" , end = " " )
for item in subset:
print (item, end = " " )
print ( "]," , end = " " )
|
C#
using System;
using System.Collections.Generic;
namespace Subsets {
public class GFG {
static List<List< string > > GetSubsets(List< string > set ,
int index)
{
List<List< string > > allSubsets;
if (index < 0) {
List< string > emptyList = new List< string >();
allSubsets
= new List<List< string > >{ emptyList };
}
else {
allSubsets = GetSubsets( set , index - 1);
string item = set [index];
List<List< string > > moreSubsets
= new List<List< string > >();
foreach (List< string > subset in allSubsets)
{
List< string > newSubset = new List< string >();
foreach ( string it in subset)
{
newSubset.Add(it);
}
newSubset.Add(item);
moreSubsets.Add(newSubset);
}
foreach (List< string > it in moreSubsets)
{
allSubsets.Add(it);
}
}
return allSubsets;
}
static void Main( string [] args)
{
List< string > set
= new List< string >{ "a" , "b" , "c" };
int index = set .Count - 1;
List<List< string > > result = GetSubsets( set , index);
foreach (List< string > it in result)
{
Console.Write( "[ " );
foreach ( string itr in it)
{
Console.Write(itr + " " );
}
Console.Write( "], " );
}
}
}
}
|
Javascript
function getSubset(set, index) {
let allSubsets = [];
if (index < 0) {
let v = [];
allSubsets.push(v);
} else {
allSubsets = getSubset(set, index - 1);
let item = set[index];
let moreSubsets = [];
for (let subset of allSubsets) {
let newSubset = [];
for (let it of subset)
newSubset.push(it);
newSubset.push(item);
moreSubsets.push(newSubset);
}
for (let it of moreSubsets)
allSubsets.push(it);
}
return allSubsets;
}
let set = [ "a" , "b" , "c" ];
let index = set.length - 1;
let result = getSubset(set, index);
for (let it of result) {
console.log( " [ " + it.join( "," ) + " ]," );
}
|
Output[[], [a], [b], [a, b], , [a, c], [b, c], [a, b, c]]
Time Complexity: O(n*2n)
Auxiliary Space: O(n), For recursive call stack
Iterative program for the power set.