我正在创建一个递归算法,以便能够从那里创建电源组。我的意思是,如果输入3为{{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}}的幂集。目前,我的算法只能工作到3,但在某种程度上它是硬编码的,最后的SOP行打印出1,2,3,}}。我似乎无法弄清楚如何以递归方式实现超过3个元素。
Public static void main(String[]args){
int elements = 0;
while(elements!=-1){
System.out.println("What's the number of elements? ");
elements= scan.nextInt();
if(elements==-1){
System.out.println("Terminate. ");
break;
}
System.out.print("{");
lab5(elements,0);
System.out.print("}" );
System.out.print("}");
System.out.println();
}
}
}
static void lab5(int a,int b){
String cur = "{";
String curBack = "}";
if(a==0){
System.out.print(cur+curBack);
}
else if(a>0){
System.out.print(cur+a+curBack);
String phrase = null;
b = a-1;
if(a==b){
b=a-2;
}
phrase = cur+a+", "+b+curBack;//a problem might be
b = a-2;
if(b==0){
phrase = "";
}
if(a==b){
b=a-2;
}
System.out.print(phrase);
lab5(a-1,b);
System.out.print(a+",");