【組合問題的原理與其遞迴實現】

來源:互聯網
上載者:User

以在n個數中選取m(0<m<=n)個數為例,問題可分解為:
1. 首先從n個數中選取編號最大的數,然後在剩下的n-1個數裡面選取m-1個數,直到從n-(m-1)個數中選取1個數為止。
2. 從n個數中選取編號次小的一個數,繼續執行1步,直到當前可選編號最大的數為m。

很明顯,上述方法是一個遞迴的過程,也就是說用遞迴的方法可以很乾淨利索地求得所有組合。

下面是遞迴方法的實現:
/// 求從數組a[1..n]中任選m個元素的所有組合。
/// a[1..n]表示候選集,n為候選集大小,n>=m>0。
/// b[1..M]用來儲存當前組合中的元素(這裡儲存的是元素下標),
/// 常量M表示滿足條件的一個組合中元素的個數,M=m,這兩個參數僅用來輸出結果。


#include <iostream>using namespace std;void combine( int a[], int n, int m,  int b[], const int M ){    for(int i=n; i>=m; i--)   // 注意這裡的迴圈範圍    {        b[m-1] = i - 1;        if (m > 1)            combine(a,i-1,m-1,b,M);        else                     // m == 1, 輸出一個組合        {            for(int j=M-1; j>=0; j--)                cout << a[b[j]] << " ";            cout << endl;        }    }}int main(){    const int N = 4;    int a[N];    for(int i=0; i<N; i++)        a[i] = i+1;    for(int M=1; M <= 4; M++)    {        //遞迴方法        int b[M];        combine(a,N,M,b,M);    }    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.