Description
Generate all the subsets of {A, B, …, } of n elements. There are 2n subsets in total. You should guarantee that the output follows the lexicographical order.
Input
An integer n (n<=9).
Output
Output all the subsets of {A, B, …, } of n elements. In each subset, the elements should be printed from smallest to largest.
Sample Input
3
Sample Output
A
AB
ABC
AC
B
BC
C
Hint
The first line in the sample output is a blank line, which corresponds to an empty set.
Yizuodi的答案(未递归实现)
#include <iostream>
#include <sstream>
#include <set>
using namespace std;
int main()
{
int num;
cin>>num;
string s[num];
int subsetnum=1;
for (int i = 0; i < num; i++)
{
s[i]='A'+i;
subsetnum*=2;
}
multiset<string> sset;
for (int i = 0; i < subsetnum; i++)
{
stringstream ss;
int binarydata = i;
int j = 0;
while(binarydata)
{
if (binarydata & 1)
{
ss<<s[j];
}
binarydata >>= 1;
j++;
}
string tmp;
ss>>tmp;
sset.insert(tmp);
}
for(multiset<string>::iterator it=sset.begin();it!=sset.end();++it){
cout<<(*it)<<endl;
}
}