集合所有子集

//我的方法
#include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
void fun(vector<int> &a, int i)
{
     if (i == 0)
     {
          cout << '@' << endl;
          return;
     }
     int k = 0;
     while (i)
     {
          if (i % 2)
          {
               cout << a[k] << ' ';
          }
          k++;
          i /= 2;
     }
     cout << endl;
}
int main(void)
{
     vector<int> a = {1, 2, 3};
     for (int i = 0; i < pow(2, a.size()); i++)
     {
          fun(a, i);
     }
}
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
#include <iostream>
                                                                                                                                                                   using namespace std;
const int ListLength = 10;
// const int ListLength=3;

//输出Buffer集合
void Output(char *Buffer, int flag)
{
     static int count = 1;
     if (count == 1)
     {
          cout << count++ << ": { }" << endl;
     }
     cout << count++ << ": {";
     for (int i = 0; i <= flag; i++)
     {
          cout << Buffer[i];
     }
     cout << "}" << endl;
}
//找到元素c在集合List中的位置
int Index(char *List, char c)
{
     for (int i = 0; i <= ListLength - 1; i++)
     {
          if (c == List[i])
          {
               return i;
               break;
          }
     }
     return -1;
}

void SubSet(char *List, int m, char *Buffer, int flag)
{
     if (m <= ListLength - 1)
     {
          /*if(m==0)
          {
                  Buffer[0]=List[0];
          }*/
          // Buffer[flag]=List[m];
          /*if(flag==0)
          {
                Buffer[flag]=List[m];
          }*/

          for (int i = (flag == 0) ? 0 : Index(List, Buffer[flag - 1]) + 1; i <= ListLength - 1; i++)
          //当flag==0时,Buffer中没有任何元素,此时i=[0...ListLength-1]
          //当flag>0时,找到Buffer中的最后一个元素在集合List中的位置i,把[i....ListLength-1]
          //处的元素,加到Buffer元素的最后面
          {
               Buffer[flag] = List[i];
               Output(Buffer, flag);
               SubSet(List, m + 1, Buffer, flag + 1);
          }
     }
     return;
}

int main()
{
     char List[ListLength] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
     // char List[ListLength]={'a','b','c'};
     char Buffer[ListLength] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
     // char Buffer[ListLength]={' ',' ',' '};
     // int flag=0;
     // TEST
     // cout<<Index(List,'c'); OK
     SubSet(List, 0, Buffer, 0);
     system("pause");
     return 0;
}
posted @ 2021-11-18 20:11  Zupernova  阅读(46)  评论(0编辑  收藏  举报