打印一个集合的幂集C++实现

问题:打印一个集合的幂集?

分析:可自行百度幂集的定义,简单点说就是打印一个集合(此处用英文字母代替)的所有子集(包括空集)。

例如:集合 {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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值