题目:输入一个字符串,打印出该字符串的所有子集。

举例:输入字符串ab,则输出ab所有的子集{a b},{a},{b},{}。

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

//获取n个元素的子集
void GetAllSubset(char *a, int *mask, int size, int c)
{
    if (size == c)
    {
        cout<<"{ ";
        for (int i = 0; i < size; i++)
        {
            if (mask[i])
            {
                cout<<a[i]<<" ";
            }
        }
        cout<<"}"<<endl;
    }
    else
    {
        mask[c] = 1;
        GetAllSubset(a, mask, size, c + 1);
        mask[c] = 0;
        GetAllSubset(a, mask, size, c + 1);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    char arr[] = {'a', 'b', 'c'};
    int mask[3] = {0};
    GetAllSubset(arr, mask, 3, 0);

    cout<<endl;
    return 0;
}

运行界面如下:

求n个元素的所有子集

相关文章:

  • 2022-12-23
  • 2021-09-14
  • 2021-08-30
  • 2021-12-15
  • 2022-12-23
  • 2021-09-15
猜你喜欢
  • 2021-10-13
  • 2021-12-20
  • 2021-06-18
  • 2022-12-23
  • 2021-11-27
  • 2021-08-09
  • 2021-08-09
相关资源
相似解决方案