您的位置:首页 > 其它

Ch8.3: find all the subsets of a set

2014-01-30 04:01 363 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐