谢谢各位!我的意思是比如说我要用所有26个字母组成一个5位的字符串,比如
aaaaa
aaaab
aaaba
aaabb
aabaa
aabab
.....
把所有可能组合都列出来,这个例子是五位的,我要求的是任意位数的所有可能组合情况,谁能通过算法把所有可能都列出来,然后在结果都加上相同的字符串,比如说
aaaaa!!!
aaaab!!!
aaaba!!!
aaabb!!!
aabaa!!!
aabab!!!
.....
最后存成一个文本文件。帮帮我吧!

解决方案 »

  1.   

    好easy呀,学过组合数学吗?上面有组合和排列的经典算法。
      

  2.   

    // iLong 要生成串的位数
    // strAppend 结尾要加的字符
    // 返回生成的列表
    function CreateList(iLong : Integer; strAppend : String) : TStrings;
    var
      iListLong,iLoop,i : integer;
      strlistRet : TStringList;
    begin
      strlistRet := TStringList.Create ;
      for i :=ord('a') to ord('z') do
      begin
        strlistRet.Add(chr(i));
      end;
      for iLoop := 2 to iLong do
      begin
        for iListLong := 0 to strlistRet.Count -1 do
        begin
          for i :=ord('a') to ord('z') do
          begin
            strlistRet.Add(strlistRet[iListLong]+chr(i));
          end;
        end;
      end;
      for i:= 0 to strlistRet.Count -1 do
        strlistRet[i]:=strlistRet[i]+strAppend;
      Result := strlistRet;
    end;
      

  3.   

    呵呵,我写的找不到了。抄一段给你。#include <iostream>
    #include <vector>
    #include <list>
    using namespace std;typedef vector<int> IntArray;// 回溯搜索生成组合
    void Search(int m, int n, int depth, IntArray& , IntArray& L, list<IntArray>& result)
    {
        if( depth == n ) {
            result.push_back(L);    
        } else {
            int begin;
            if( depth == 0 ) {
                begin = 0;
            } else {
                begin = L[depth-1];
            }
            for( int i = begin; i < m; i++ ) 
                if( [i] == 0 ) {
                    [i] = 1;
                    L[depth] = i + 1;
                    Search( m, n, depth+1, , L, result );
                    [i] = 0;
                }
        }
    }
    // 生成从m个数中取出n个数的组合数C(m,n)
    // 结果在result中返回
    void Combination(int m, int n, list<IntArray>& result)
    {            
        if( m < n ) return;    IntArray (m);          // 用来标记某个数字是否用过了
        
        for( int i=0; i < m; i++ ) { // 初始化
            .push_back(0);
        }
        
        IntArray comb(n);      // 存储一组组合数  
    comb.clear();
        comb.resize(n);
        
        Search(m, n, 0, , comb, result);
    }
    // 打印组合数
    void Print(list<IntArray>& combs)
    {
        cout << "result is : " << endl;    list<IntArray>::iterator iter;
        for( iter = combs.begin(); iter != combs.end(); iter++ ) 
        {
            IntArray& array = *iter;
            for( int i = 0; i < array.size(); i++ )        
                cout << array[i] << " ";
            cout << endl;
        }
    }int main()
    {
        
        int m, n;
    list<IntArray> result;    cout << "input m : ";
        cin >> m;
        cout << "input n : ";
        cin >> n;        Combination( m, n, result );        
        Print( result );
      return 0;