全排列

给定一个字符串,要求给出其所有的排列。例如给出“ABC”,则其排列有:ABC,ACB,BAC,BCA,CAB,CBA 6种。这是一个看似简单,但是实现起来却不是很容易的问题。记得去年一个师姐去参加某NB公司的笔试的时候就被这样一个问题给整了,更加郁闷的是别人是把程序都给出了,给出了输入,要给出输出。结果是倒弄了半天,最后发现是求解全排列,郁闷不已!

解法一:经典的解法,也叫“后补法”:

void Permutation2(char* a, int m, int n)

{

       int i;

       char t;

 

       if (m < n-1)

       {

              Permutation2(a, m + 1, n);

 

              for (i = m + 1; i < n; i++)

              {

                     t    = a[m];

                     a[m] = a[i];

                     a[i] = t;

 

                     Permutation2(a, m + 1, n);

                    

                     t    = a[m];

                     a[m] = a[i];

                     a[i] = t;

              }

       }

       else

       {

              cout<<a<<endl;

       }

}

解法二::循环左移,这是全排列的一个特性。实现代码为:

void CircleLeftShit(char* str,int m)

{

       int i;

       char temp = str[0];

 

       for (i = 0; i < m - 1; i++)

       {

              str[i] = str[i+1];

       }

 

       str[i] = temp;

}

 

 

void Permutation(char* str,int m,int n)

{

       if (m < n)

       {

              for (int k = 0; k <= m; k++)

              {

                     Permutation(str,m + 1,n);

 

                     CircleLeftShit(str,m);

              }

       }

       else

       {

              cout<<str<<endl;

       }

      

}

以下给出一个测试程序:

int main(int argc,char* argv[])

{

       char str[]="ABC";

      

       Permutation(str,0,3);

 

       cout<<"......."<<endl;

 

       Permutation2(str,0,3);

 

       return 0;

}

      

posted @ 2010-02-01 21:49  blessw  阅读(206)  评论(0编辑  收藏  举报