面試題精選(64):元素可重複的群組合演算法

來源:互聯網
上載者:User

可重複的群組合問題是指,在計算(產生)組合時可以允許元素重複的一類組合問題。例如,對於有四個元素的集合{a, b, c, d},其可重複的群組合C(4, 3)有20個:aaa, aab, aac, aad, abb, abc, abd, acc, acd, add, bbb, bbc, bbd, bcc, bcd, bdd, ccc, ccd, cdd, ddd。

用P(n, k)表示從n個元素中選出k個元素(允許重複)的組合問題,那麼此問題可以分解為兩個子問題:P(n, k-1)和P(n-1, k),
解釋如下:
P(n, k)中n個元素的所有k元素組合可以分成兩部分。
第一部分的每個組合均以第一個元素開始,再串連上k-1個元素的組合,即再串連上P(n,k-1)的每一個組合;
第二部分的每個組合不含有第一個元素,即P(n-1, k)中的每一個組合(此時元素為後n-1個元素)。
因此,P(n, k)分解為P(n, k-1)和P(n-1, k)。

如果用f(n, k)表示P(n, k)中的組合數,那麼有:
(1)當k = 1時,f(n, k) = n
(2)當n = 1時,f(n, k) = 1
(3)當k > 1且n > 1時,f(n, k) = f(n, k -1) + f(n-1, k)

此外,有公式f(n, k) = C(n + k -1, k)(表示n+k-1選k的組合數,沒有重複元素),這可以用歸納法證明,這裡就不囉嗦了。

C++實現如下:

F:/tmp>type ttt.cpp
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cassert>
using namespace std;

template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k,
    vector<ElemType> &pre)
{
    if (k == 1) {
        for (int i = 0; i < num; ++i) {
            copy(pre.begin(), pre.end(), ostream_iterator<ElemType>(cout));
            cout << elements[i];
            cout << endl;
        }
        return;
    }

    if (num == 1) {
        ostream_iterator<ElemType> outIter(cout);
        outIter = copy(pre.begin(), pre.end(), outIter);
        fill_n(outIter, k, elements[0]);
        cout << endl;
        return;
    }

    pre.push_back(elements[0]);
    CalcRepeatableCombination(elements, num, k - 1, pre);
    pre.pop_back();

    CalcRepeatableCombination(elements + 1, num - 1, k, pre);
}

template <typename ElemType>
void CalcRepeatableCombination(const ElemType elements[], int num, int k)
{
    assert(num >= k && k >= 1);
    vector<ElemType> one;
    CalcRepeatableCombination(elements, num, k, one);
}

int main()
{
    char elements[] = {'a', 'b', 'c', 'd'};
    CalcRepeatableCombination(elements, 4, 3);
}

F:/tmp>g++ ttt.cpp

F:/tmp>a.exe
aaa
aab
aac
aad
abb
abc
abd
acc
acd
add
bbb
bbc
bbd
bcc
bcd
bdd
ccc
ccd
cdd
ddd

聯繫我們

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