问题:打印一个集合的幂集?
分析:可自行百度幂集的定义,简单点说就是打印一个集合(此处用英文字母代替)的所有子集(包括空集)。
例如:集合 {A,B,C}的幂集为ABC, AB#, A#C, A##, #BC, #B#, ##C, ###, 其中#表示空
之前去一家公司面试的时候碰到的一道题,当时也想到了应该用递归,不过细节没考虑好,导致当时很囧地做不出来。回来之后花了10分钟写一个,不一定是做好的做法。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void PrintPowerSet(char word, int kth, string f)
{
string s1 = f + word;
string s2 = f + '#';
if(kth > 1)
{
PrintPowerSet(word+1, kth-1, s1);
PrintPowerSet(word+1, kth-1, s2);
}
else
{
cout << s1 << endl;
cout << s2 << endl;
}
}
int main(int argc, char const *argv[])
{
int k = 3;
string s1;
if(argc == 2)
{
k = atoi(argv[1]);
if(k >= 17)
{
k = 3;
}
}
PrintPowerSet('A', k, s1);
return 0;
}
参数解释:word表示当前要打印的字母(从A开始),kth表示要打印kth个,string f表示上次调用的字符串信息。
以上程序在ubuntu14.04上使用g++编译通过,打印17个字母需要的时间如下:
time -p ./run_powerset 17 > file.txt
real 5.10
user 0.12
sys 4.96