Feng.Li's Java See

抓紧时间,大步向前。
随笔 - 95, 文章 - 4, 评论 - 58, 引用 - 0
数据加载中……

全排列的递归算法

void perm(char *list, int i, int n){
int j,temp;
if(i == n){
for(j = 0; j < n; j++)
cout<<list[j];
cout<<" ";
}
else{
for(j = i; j < n; j++){
SWAP(list[i],list[j],temp);
perm(list,i+1,n);
SWAP(list[i],list[j],temp);
}

for(j = i; j < n; j++){
SWAP(list[i],list[j],temp); //将第j数字做为第一个
perm(list,i+1,n);
SWAP(list[i],list[j],temp); //将第j数字换回原来位置,准备用第j+1个做做为第一个

}
-----------------------------------------------------------
建议你将函数修改成以下形式,自己观察一下
-----------------------------------------------------------
void perm(char *list, int i, int n){
int j,temp;
for(j = 0; j < n; j++)
cout<<list[j]<<endl;
if(i == n){
for(j = 0; j < n; j++)
cout<<list[j];
cout<<" "<<i=n了<<" ";
}
else{
for(j = i; j < n; j++){
SWAP(list[i],list[j],temp);
perm(list,i+1,n);
SWAP(list[i],list[j],temp);

}
========================================================================================================

下面是完整的程序:C#

using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] list = {'a','b','c','d' };
            perm(list, 0, 4);
            Console.ReadLine();
        }
        static void perm(char[] list, int i, int n)
        {
            int j,temp;
            if(i==n)
            {
             
                for(j=0;j<n;j++)
                {
                    Console.Write(list[j]);
                    //Console.WriteLine();
                }
            }
            else

               
            {
               
                for (j=i;j<n;j++)
                {
                    swap(ref list[i],ref list[j]);
                    perm(list,i+1,n);
                    swap(ref list[i], ref list[j]);
                }
            }
        }
        static void swap(ref char  a, ref char  b)
        {
            char c = a;
            a = b;
            b = c;
           
          
        }
    }
}


posted on 2007-10-09 08:58 小锋 阅读(441) 评论(0)  编辑  收藏 所属分类: algorithm


只有注册用户登录后才能发表评论。


网站导航: