Ch8.3: find all the subsets of a set

本文详细介绍了如何使用位运算和递归来解决集合子集问题,包括了子集的数量计算、子集的生成以及递归解决方法的实现。通过实例演示了从全集到空集的子集生成过程,以及如何通过位操作来表示每个子集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this problem, We can still use the power of BINARY number to represent the nth number is shown or not.

For example:

{2, 0, 1, 4}, if I use _ _ _ _ (4 bits) to represent each numbers. Then I can have 2^4 combinations. eg.: 1011 means {2, 1, 4}, 0010 means {1}, 0000 means {empty}.


Another method is recursion. Because this problem can be divide into small problems and solve it.

Whole code:

// hawstein ch 8-3: subsets of a set

#include 
#include 

using namespace std;


// method 1: {1,2,3,4} have 4 elements so have 2^n-1=2^4-1=15 subsets
// according: they can be represented by shown/not shown, or say by 0000~1111
// TIPS: 2^n can be represented by 1<> vvi;
typedef vector vi;

vvi get_subsets(int a[], int n){
    vvi big_subsets;
	int m = 1<0){
			if(j&1)
				small_subsets.push_back(a[idx]);
			j>>=1;
			++idx;
		}
		big_subsets.push_back(small_subsets);
	}
	return big_subsets;
}

// method 2: recursion. This problem can be deductive from hard problem to small 
// ones: for example:
// {1,2} has subsets: {},{1},{2},{1,2}
// {1,2,3} has subsets: {},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}
// subsets(1,2,3)-subsets(1,2) = {3},{1,3},{2,3},{1,2,3}
// {3},{1,3},{2,3},{1,2,3} = {},{1},{2},{1,2} and add {3} in them.

vvi get_subsets1(int a[], int n, int idx){
	vvi big_subsets;
	if(idx==n) {
		vi small_subsets;
		big_subsets.push_back(small_subsets); // empty set
	}
	else{
		vvi tmp_big_subsets = get_subsets1(a, n, idx+1);
        int tmp = a[idx];
		for(int i=0; i

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值