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