用递归的方法实现全排列

举例说明,排头为1时:
Perm(1,4) : for j=1  to  4
j=1: P[1]与P[1]互换     1  2  3  4
Perm(2,4) : for j=2  to  4
j=2: P[2]与P[2]互换 1  2  3  4
Perm(3,4): for j=3  to  4
j=3: P[3]与P[3]互换 1  2  3  4
Perml(4,4):输出1  2  3  4
P[3]与P[3]互换
j=4: P[4]与P[3]互换: 1  2   4  3
Perml(4,4):输出1  2  4   3
P[4]与P[3]互换 : 1  2  3  4
j=3: P[3]与P[2]互换 1 3  2  4
Perm(3,4): for j=3  to  4
j=3: P[3]与P[3]互换 1  3  2  4
Perml(4,4):输出1  3  2   4;
P[3]回位; P[3]与P[3]互换:
j=4: P[4]与P[3]互换 1  3   4   2
Perml(4,4):输出1  3   4   2 ;
P[4]回位; P[4]与P[3]互换:
下面附带我的代码:

#include<stdio.h>
int a[100];
void perm(int m,int n)
{
	int i,temp;
	if(m==n)
	{
		for(i=1;i<=n;i++)
			printf("%d ",a[i]);
		printf("\n");
	}
	else{
		for(i=m;i<=n;i++)
		{
			temp=a[m];
			a[m]=a[i];
			a[i]=temp;
			perm(m+1,n);
			temp=a[m];
			a[m]=a[i];
			a[i]=temp;
		}
	}
}
int main()
{
	int n,i;
	while(scanf("%d",&n),n!=0)
	{
		for(i=1;i<=n;i++)
			a[i]=i;
		perm(1,n);
	}
	return 0;
}


 

原文地址:https://www.cnblogs.com/yyf573462811/p/6365328.html