求一个字符串的所有子集
如“abcd”需打印出:
a,b,c,d
ab,ac,ad,bc,bd,cd
abc,abc,acd,bcd
[解决办法]
void OutPut(char *dest){ for(; *dest; dest++) cout<<*dest<<" "; cout<<endl;}void GetPowerSet(int i, char A[], char B[]){ if( i==strlen(A) ) OutPut(B); else { char x=A[i]; //GetElem int k=strlen(B); B[k]=x; GetPowerSet(i+1, A, B); //左子树 B[k]='0'; GetPowerSet(i+1, A, B); //右子树 }}int main(){ char A[]={"123"}; int size_B=strlen(A)+1; char* B=new char[size_B]; memset(B, 0, size_B); GetPowerSet(0, A, B); delete B; return 0;}
[解决办法]
#1楼输出格式没有按照要求,如果要严格按照字符长度依次输出:
public class Powerset { public static int line = 0; public static void print(String s){ if(s.length()>line){ System.out.format("%n%s",s); line++; } else { System.out.format(",%s",s); } } public static void subselect(String s,String text,int i,int k){ if(k==0){ print(s); }else{ char c = text.charAt(i); i++; if(i>=text.length()){ if(k==0)print(s); else if(k==1)print(s+c); }else{ subselect(s+c,text,i,k-1); subselect(s,text,i,k); } } } public static void solve(String text){ char c = text.charAt(0); for(int k=0;k<text.length()-1;k++){ subselect(c+"",text,1,k); subselect("",text,1,k+1); } } public static void main(String[] args) { Powerset.solve("abcd"); }}
[解决办法]
求1L给个注释,或者分析
[解决办法]