#include <iostream>
#include <math.h>
using namespace std;
int n; //집합내 원소들의 총 개수
char* items; //집합을 문자로 저장할 공간
/**
@brief 주어진 집합의 모든 부분집합을 구하는 함수
@param 현재의 부분집합을 저장할 배열, 그 배열의 인덱스, 함수의 흐름
@author http://shoner.pe.kr
*/
void powerSet(char* aSet, int aSetLen, int current)
{
// 완성된 부분집합 하나를 출력하는 부분
if(current==n)
{
cout << "{";
for(int i=0; i<aSetLen;i++)
cout << aSet[i] << " ";
cout << "}" << endl;
}
// 재귀적 호출을 통해 하나의 부분집합을 완성하는 부분
else {
current++;
powerSet(aSet, aSetLen, current);
current--;
aSet[aSetLen++]=items[current++];
powerSet(aSet, aSetLen, current);
}
}
int main(int argc, char **argv)
{
//집합내의 원소들의 개수를 입력받음
cout << "Input the SIZE of Set : " ;
cin >> n;
if(n<0)
{
cout << " size wrong !! " << endl;
return 0;
}
items = new char[n];
//원소들을 하나씩 입력 받음 (문자 하나)
for(int i=0; i<n;i++)
{
cout << "Insert a element - " << i+1 << " : ";
cin >> items[i];
}
//부분집합 하나를 저장할 수 있는 공간 할당
char* aSet;
aSet = new char[n];
//부분집합 구하는 함수 호출
powerSet(aSet, 0, 0);
cout << "all subsets No : 2^" << n << "=" << pow(2.0,n) << endl;
return 0;
}
+실제 실행과정을 보기 쉽게 표현해 보면 아래와 같음.