一个C语言全排列的算法。 比如,输入3,则将123的全排列全部输出:123,132,213,231
2013-07-23
展开全部
#include
main()
{
int a1,a2,a3,a4,a5,a6,a7,a8,a9,n,t=0;
scanf("%d",&n);
for(a1=1;a1<=n;a1++)
if(n==1){printf("%d\n",a1);t=t+1;}
else
for (a2=1;a2<=n;a2++)
if(a2!=a1)
{if(n==2) {printf("%d%d\n",a1,a2);t=t+1;}
else
for (a3=1;a3<=n;a3++)
if(a3!=a2&&a3!=a1)
{if(n==3) {printf("%d%d%d\n",a1,a2,a3);t=t+1;}
else
for (a4=1;a4<=n;a4++)
if(a4!=a3&&a4!=a2&&a4!=a1)
{if(n==4) {printf("%d%d%d%d\n",a1,a2,a3,a4);t=t+1;}
else
for (a5=1;a5<=n;a5++)
if(a5!=a4&&a5!=a3&&a5!=a2&&a5!=a1)
{if(n==5) {printf("%d%d%d%d%d\n",a1,a2,a3,a4,a5);t=t+1;}
else
for (a6=1;a6<=n;a6++)
if(a6!=a5&&a6!=a4&&a6!=a3&&a6!=a2&&a6!=a1)
{if(n==6) {printf("%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6);t=t+1;}
else
for (a7=1;a7<=n;a7++)
if(a7!=a6&&a7!=a5&&a7!=a4&&a7!=a3&&a7!=a2&&a7!=a1)
{if(n==7) {printf("%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7);t=t+1;}
else
for (a8=1;a8<=n;a8++)
if(a8!=a7&&a8!=a6&&a8!=a5&&a8!=a4&&a8!=a3&&a8!=a2&&a8!=a1)
{if(n==8) {printf("%d%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7,a8);t=t+1;}
else
for (a9=1;a9<=n;a9++)
if(a9!=a8&&a9!=a7&&a9!=a6&&a9!=a5&&a9!=a4&&a9!=a3&&a9!=a2&&a9!=a1)
{if(n==9) {printf("%d%d%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7,a8,a9);t=t+1;}
}
}
}
}
}
}
}
}
printf("共有%d种\n",t);
getchar();getchar();
}
自己辛辛苦苦写的,用dev c运行成功
main()
{
int a1,a2,a3,a4,a5,a6,a7,a8,a9,n,t=0;
scanf("%d",&n);
for(a1=1;a1<=n;a1++)
if(n==1){printf("%d\n",a1);t=t+1;}
else
for (a2=1;a2<=n;a2++)
if(a2!=a1)
{if(n==2) {printf("%d%d\n",a1,a2);t=t+1;}
else
for (a3=1;a3<=n;a3++)
if(a3!=a2&&a3!=a1)
{if(n==3) {printf("%d%d%d\n",a1,a2,a3);t=t+1;}
else
for (a4=1;a4<=n;a4++)
if(a4!=a3&&a4!=a2&&a4!=a1)
{if(n==4) {printf("%d%d%d%d\n",a1,a2,a3,a4);t=t+1;}
else
for (a5=1;a5<=n;a5++)
if(a5!=a4&&a5!=a3&&a5!=a2&&a5!=a1)
{if(n==5) {printf("%d%d%d%d%d\n",a1,a2,a3,a4,a5);t=t+1;}
else
for (a6=1;a6<=n;a6++)
if(a6!=a5&&a6!=a4&&a6!=a3&&a6!=a2&&a6!=a1)
{if(n==6) {printf("%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6);t=t+1;}
else
for (a7=1;a7<=n;a7++)
if(a7!=a6&&a7!=a5&&a7!=a4&&a7!=a3&&a7!=a2&&a7!=a1)
{if(n==7) {printf("%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7);t=t+1;}
else
for (a8=1;a8<=n;a8++)
if(a8!=a7&&a8!=a6&&a8!=a5&&a8!=a4&&a8!=a3&&a8!=a2&&a8!=a1)
{if(n==8) {printf("%d%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7,a8);t=t+1;}
else
for (a9=1;a9<=n;a9++)
if(a9!=a8&&a9!=a7&&a9!=a6&&a9!=a5&&a9!=a4&&a9!=a3&&a9!=a2&&a9!=a1)
{if(n==9) {printf("%d%d%d%d%d%d%d%d%d\n",a1,a2,a3,a4,a5,a6,a7,a8,a9);t=t+1;}
}
}
}
}
}
}
}
}
printf("共有%d种\n",t);
getchar();getchar();
}
自己辛辛苦苦写的,用dev c运行成功
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询