組合演算法問題

來源:互聯網
上載者:User

標籤:

一、問題描述

如輸入字串“abc”,其中字串的元素是不重複的,那麼它的所有組合是a,b,c,ab,ac,bc,abc共七種。

 

二、問題分析

這個問題是個數學問題,根據所學的知識,所有組合的情況是2^n-1。我們可以利用C語言中的按位操作符進行分析。如abc,

用二進位表示可以有如下幾種:000,001,010,011,100,101,110,111.當然要去掉000這種,其餘剛好是7種。我們可以把1看成取對應位置的元素,如001代表c,110代表ab,111代表abc.

 

三、程式設計

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>


using namespace std;


int num=0;

bool compare(const string &s1,const string &s2)    //字串大小的比較方式,按照字串的長度比較
{
           return s1.size()<s2.size();                        //按照字串長度從小到大排序
}


void main()
{
       string in_s;

       vector<string> out_s;                     //儲存字元向量

       cout<<"請輸入一個字串:"<<endl;
       cin>>in_s;

       int length=in_s.size();
       int number=1<<length;                  //如abc,長度是3,此時number=1000,對應十進位是8

       for(int i=1;i<number;i++)               //組合的可能數,按照上述分析,i=1-7,正好是所有的情況
       {
              string temp_s;                        //臨時變數,空的字串

              for(int j=0;j<length;j++)         //每種情況下的各個位置的字元,分別用001,010,100去讀取每個位置的數
              {
                     if(i&(1<<j))                      //如果對應的位置是1,代表該字元輸出
                          temp_s+=in_s[j];
              }

              num++;                                  //數目加1

              out_s.push_back(temp_s);        //壓入向量容器中
        }

        sort(out_s.begin(),out_s.end());       //按照字典順序進行排列,C++已有的泛型演算法
        stable_sort(out_s.begin(),out_s.end(),compare);    //按照字串的長度進行排列,compare函數已經定義了

        for(int i=0;i<out_s.size();i++)         //輸出組合的情況
                 cout<<out_s[i]<<endl;

        cout<<"組合數目:"<<num<<endl;   //輸出組合的數目

        while(1);
}

 

四、程式結果

組合演算法問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.