求集合的子集、全排列总结

一、输出n个元素的集合所有的子集,如{a,b,c}的子集就有{},{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c}。

方法1:利用2进制表示

/*
对于集合{A,B,C,D},它的非空子集个数为2×2×2×2-1,用二进制表示就是1111,我们规定从左到右第1位对应A,
第2位对应B,第3位对应C,第4位对应D。如果相应位为1,则表示存在该字符,否则不存在该字符。如1101就表示{A,B,D}。
这样,对于一个n个字符组成的集合,根据n可以算法它的非空子集个数为m(2的n次幂-1),将m转换为二进制数,然后采用每次减1的方法,即可得到所有子集。
*/ 
void SubSets(const char* str)
{
	int len = strlen(str);
	
	for(int i = 0; i < (1<<len); i++) //2^len 个子集 
	{
		cout<<"{ ";
		
		//判断数i的二进制中第1<<j位是否为1 
		for(int j = 0; j < len; j++)  
		{
			if( (i&(1<<j) ) != 0)
			{
				cout<<str[j];
			}
		}
		cout<<" }"<<endl;
	}
}
int main()
{
	const char *str = "abc";
	
	SubSets(str);
	
	system("pause");
}




 
 
方法2 :递归
void SubSets(const char* str, char out[], int curr, int start)
{
	int n = strlen(str);
	
	for(int i = start; i < n; i++)
	{
		out[curr] = str[i];
		out[curr+1] = '\0';
		
		printf("%s\n", out);
		
		if(i < n-1)
			SubSets(str, out, curr+1, i+1); 
	}
}
int main()
{
	const char *str = "abc";
	char *out = new char[strlen(str) + 1];
	memset(out, 0, strlen(str)+1);
	
	SubSets(str, out, 0, 0);
	
	system("pause");
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值