I am trying to find the powerset of a set recursively and then print the results which I am very stuck on any help would be greatly appreciated.
public static ArrayList<String> getpowerset(int a[],int n, ArrayList<String> power){
if(n<0)
{
return null;
}
if(n==0)
{
if(power==null)
power=new ArrayList<String>();
power.add(" ");
return power;
}
power=getpowerset(a, n-1, power);
ArrayList<String> tmp=new ArrayList<String>();
for(String s:power)
{
if(s.equals(" "))
tmp.add(""+a[n-1]);
else
tmp.add(s+a[n-1]);
}
power.addAll(tmp);
return power;
for (int i = 0; i<power.size();i++){
System.out.println(power);
}
Try to think recursively:
firstElemnt
] +restOfTheList
is the powerset ofrestOfTheList
plus each element of the powerset ofrestOfTheList
chained withfirstElemnt
Example:
Given a list [a,b,c]:
a
to each element of previous powerset)b
to each element of previous powerset)c
to each element of previous powerset)ALGORITHM
TEST
OUTPUT
Note that i have imported the following classes: