n个对象的排列(具有重复的排列)

时间:2010-09-29 16:04:30

标签: algorithm math combinatorics

我正在寻找“排列”算法的快速实现(具有重复的排列)。 给定N个对象(数量a中的A,数量b中的B,......),生成所有可能的组合 例如:

Arrangement("AAA", "B", "CC") would return :   
"AAABCC" "AABACC" "AABCAC" "AABCCA" "ABAACC" "ABACAC" "ABACCA" "ABCAAC"   
"ABCACA" "ABCCAA" "BAAACC" "BAACAC" "BAACCA" "BACAAC" "BACACA" "BACCAA"   
"BCAAAC" "BCAACA" "BCACAA" "BCCAAA" "AAACBC" "AACABC" "AACBAC" "AACBCA"   
"ACAABC" "ACABAC" "ACABCA" "ACBAAC" "ACBACA" "ACBCAA" "CAAABC" "CAABAC"   
"CAABCA" "CABAAC" "CABACA" "CABCAA" "CBAAAC" "CBAACA" "CBACAA" "CBCAAA"   
"AAACCB" "AACACB" "AACCAB" "AACCBA" "ACAACB" "ACACAB" "ACACBA" "ACCAAB"   
"ACCABA" "ACCBAA" "CAAACB" "CAACAB" "CAACBA" "CACAAB" "CACABA" "CACBAA"   
"CCAAAB" "CCAABA" "CCABAA" "CCBAAA"  

(C中的代码,C#或Pascal,如果可能)

提前致谢
菲利普

1 个答案:

答案 0 :(得分:6)

如果你可以使用C ++,它已经在标准库中提供了:

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

int main() { 
    std::string a("AAABCC");

    do {
        std::cout << a << "\t";
    } while (std::next_permutation(a.begin(), a.end()));
    return 0;
}

编辑:此输出为:

AAABCC AAACBC AAACCB AABACC AABCAC AABCCA AACABC AACACB AACBAC AACBCA AACCAB AACCBA ABAACC ABACAC ABACCA ABCAAC ABCACA ABCCAA ACAABC ACAACB ACABAC ACABCA ACACAB ACACBA ACBAAC ACBACA ACBCAA ACCAAB ACCABA ACCBAA BAAACC BAACAC BAACCA BACAAC BACACA BACCAA BCAAAC BCAACA BCACAA BCCAAA CAAABC CAAACB CAABAC CAABCA CAACAB CAACBA CABAAC CABACA CABCAA CACAAB CACABA CACBAA CBAAAC CBAACA CBACAA CBCAAA CCAAAB CCAABA CCABAA CCBAAA

对于任何不能使用C ++的人,Mark Nelson几年前在C / C ++用户期刊上写了一篇article,可能会有所帮助。