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] +restOfTheListis the powerset ofrestOfTheListplus each element of the powerset ofrestOfTheListchained withfirstElemntExample:
Given a list [a,b,c]:
ato each element of previous powerset)bto each element of previous powerset)cto each element of previous powerset)ALGORITHM
TEST
OUTPUT
Note that i have imported the following classes: