递归求集合的所有子集的程序

来源:互联网 发布:创维电视调试端口用途 编辑:程序博客网 时间:2024/05/23 23:00
#include <iostream>
#include <vector>
using namespace std;
//算法描述:
//1、如果遍历完全集,打印出所有被标记为true的元素
//2、否则:
//3、取第depth个元素,即标记为true
//4、继续判断第depth+1个元素
//5、不取第depth个元素,妈标记为false
//6、继续判断第depth+1个元素
//如:集合元素为a,b,c
// 把与元素a对应的标记为true,表示要取出
//判断元素b,进入第一层递归,里面就标记b为取出,再进入递归,标记C为取出,再进入递归,打印a,b,c
//退出上一层递归,标记c不取出,进入第二个递归,由于已经遍历完,打印出ab,
//依此类推
//。。。
void getAllSubset(char str[], int size, vector<bool>  bVector, int depth);

int main()
{
char s[] = {'a', 'b', 'c'};
int size = sizeof(s) / sizeof(char);
       vector<bool> v(size, false);

       getAllSubset(s, size, v, 0);
       return 0;
}

void getAllSubset(char str[], int size, vector<bool>  bVector, int depth)
{
if (depth == size) //如果把size个数都判断完,就把取出的数打印出来
{
         for (int i = 0; i < size; i++)
         {
          if (bVector[i] != false)
                 cout << str[i] << " ";
         }
         cout << endl;
}
else
{
bVector[depth] = true;   //取第de pth个数
getAllSubset(str, size, bVector, depth+1); //判断第depth+1个数
bVector[depth] = false; //不取第depth个数
getAllSubset(str, size, bVector, depth+1); //判断第depth+1个数
}
}