天天看點

c++求集合幂集

#include <iostream>
using namespace std;

int powerset(char *a,int len)
{
	int i = 0, j = 0;
	bool flag = false;
	cout<<"{ }"<<endl;
	for(i = 1; !flag ; i++)
	{
		cout<<"{";
		flag = true;
		for(j = 0; j < len; j++)
		{
			if( (i >> j) & 1)
                cout << a[j] << " ";
			else
				flag = false;
		}
		cout << "}" <<endl;
	}
	return i;
}

int main(int argc, char*argv[])
{
	int num = 4;
    if(argc > 1){
        num = atoi(argv[1]);
    }
    char *item = new char[num];
    for(int i = 0;i < num; i++){
        item[i] = 'a' + i;
    }
	int count = powerset(item,num);
	cout << num << "個元素幂集總數:" << count <<endl;
	delete [] item;
	return 0;
}
           

輸出:

{ }

{a }

{b }

{a b }

{c }

{a c }

{b c }

{a b c }

{d }

{a d }

{b d }

{a b d }

{c d }

{a c d }

{b c d }

{a b c d }

4個元素幂集總數:16

繼續閱讀