试编写一个递归函数,用来输出n 个元素的所有子集。例如,三个元素{a, b, c} 的所有子集是:{ }(空集),{a}, {b}, {c}, {a, b}, {a, c}, {b, c} 和{a, b, c}。 #include<iostream>#include<vector>using namespace std;struct Gather{ int a,b,c; Gather(int x=0,int y=0,int z=0):a(x),b(y),c(z){}}; ostream& operator<<(ostream&os,Gather&ga){ os<<'{'; if(ga.a!=0)os<<ga.a; if(ga.b!=0)os<<ga.b; if(ga.c!=0)os<<ga.c; os<<'}'; return os;}int main(){ vector<Gather>subset; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) { int sub[3]={1,2,3}; if(i==0)sub[0]=0; if(j==0)sub[1]=0; if(k==0)sub[2]=0; Gather temp(sub[0],sub[1],sub[2]); subset.push_back(temp); } for(int n=0;n<subset.size();n++) cout<<subset[n]; return 0;}

评论