輸出一個集合所有的子集合

來源:互聯網
上載者:User

#include <iostream>
using namespace std;

const int N = 1000;

void SelSubstr(int flag[],int count)
{
 for(int i = 0;i < count;i++)
 {
  flag[i] = flag[i]^1;
  //當前元素取反後為0則停止。這樣取反正好有2^n-1種情況,而且不重複。
  if(!flag[i])
   break;
 }
}

void print(int flag[],int count,const char *str,char *subStr)
{
 int j = 0;
 for(int i = 0;i<count;i++)
 {
  if(flag[i])  //把要輸出的字元放在subStr中
   subStr[j++] = str[i];
 }
 subStr[j] = '/0';
 cout<<subStr<<endl;
}

int main()
{
 char *str = new char[N];     //原字串
 char *subStr = new char[N];  //子集臨時存放字串
 cout<<"Input a string:";
 cin.getline(str,N);
 int count = strlen(str);

 int *flag = new int[count];
 //預設開始時,設定所有元素都沒顯示
 for(int i = 0;i< count;i++)
  flag[i] = 0;
 
 cout<<"As follow is substr:"<<endl;
 int subStrCount = 0;     //統計子集的數目
 int q = 2<<(count-1);    //計算迴圈次數
 for(int i = 0;i < q;i++)
 {
  SelSubstr(flag,count);          //取子串(子集)
  print(flag,count,str,subStr); //顯示所取子串(子集)
  subStrCount++;
 }
 cout<<"total number of the subset(include Empty-set)is: "<<subStrCount<<endl;
 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.