>递归,从VChelp的算法版主那里抄来的:</P>0 R0 }8 m H% ?8 s$ ^3 N
><BR>#define N_permutation 5 // 排列元素数量</P>
>unsigned char flag[N_permutation]; // 标记元素是否被使用<BR>unsigned char dat[N_permutation]; // 记录临时元素队列<BR>unsigned char p_dat=0; // 对列指针</P>- {" v& H. I% V
>void out_dat() // 输出对列dat中的内容<BR>{<BR> for(int i=0;i<N_permutation;i++)<BR> cout<<dat<<' ';<BR> cout<<endl;<BR>}</P>; _$ _& E% ^& ^- }
>void permutation() // 再入函数,生成N_permutation个字母的所有排列,<BR>{ // 最大递归次数为N_permutation<BR> unsigned char i; // 被再入函数入栈保护的局部变量<BR> for(i=0;i<N_permutation;i++) <BR> {<BR> if (flag==0)<BR> {<BR> flag=1; // 标记元素被使用<BR> dat[p_dat]=0x41+i; // 将字母添加到队列<BR> p_dat++; </P>) R) U2 s% h N( f# U, i3 Z6 I
> if (p_dat==N_permutation) // 对列满输出,<BR> out_dat();<BR> else permutation(); // 否则继续添加<BR> p_dat--;<BR> flag=0;<BR> }<BR> } <BR>}<BR>void main()<BR>{<BR> permutation();<BR> getch();<BR>}</P>[em07][em07][em07]
>前头要加上:</P>5 [( ?( y7 g6 a
>#include <iostream><BR>#include <conio.h><BR>using namespace std;<BR></P>
>非递归实现,效率不错</P>% v1 x8 c: t1 a
>#include <iostream><BR>#include <conio.h><BR>#include <windows.h><BR>using namespace std;</P>
>void output(int *p); //输出函数<BR>void permutation(int *p);//全排列函数</P>
>int a[]={1,2,3,4,5,6,7,8,9,10,11};//待排列数组<BR>int N=sizeof(a)/sizeof(int); //数组长度<BR>int *p=a; //数组指针</P>
>void main()<BR>{<BR> permutation(p); //调用全排列函数<BR> output(p); //输出排列结果<BR> getch();<BR>}</P>
>void permutation(int *p)<BR>{<BR> bool flag=false; //标志排列是否结束<BR> int temp; //临时变量,用来交换数组元素</P>- p' o( A, `9 [. {. o
> while(1)<BR> {<BR> for(int i=0;i<N-1;i++)<BR> {<BR> flag=true; //如已排列完,falg为真</P>8 ~/ l7 ?8 l+ c3 @. ]2 l
> if(p<p[i+1]) //如果发现第一个倒序的数组元素,p[i+1]被称为倒序元素<BR> { <BR> flag=false; //说明未排列完</P>% \+ C9 |2 ]/ j) }& N1 I
> int j=0;<BR> while(p[j++]>=p[i+1]); //找到第一个大于或等于倒序元素的数组元素<BR> j-=1; </P>
> temp=p[i+1]; //交换这两个元素<BR> p[i+1]=p[j];<BR> p[j]=temp;</P>; A* h( b, a5 I2 s$ y3 M, I7 y
> j=0;<BR> while(j<(i+1)/2) //倒置倒充元素原位置以前的所有元素<BR> {<BR> temp=p[j];<BR> p[j]=p[i-j];<BR> p[i-j]=temp;<BR> <BR> j++;<BR> } <BR> break; //跳出for循环,<BR> }<BR> }<BR> if(flag) //如果排列完,结束循环<BR> break;<BR> //output(p); //输出排列结果<BR> }<BR>}</P>
>void output(int *p)<BR>{<BR> cout<<endl;<BR> for(int i=0;i<N;i++)<BR> cout<<p<<' ';</P>
>}<BR></P>| 欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) | Powered by Discuz! X2.5 |