用回溯法求解n个数的全排列。try0-try4的功能一样,都可以求出n个数的全排列,但是回溯前的清零(回收现场)语句b[j]=0的位置不一样。一般地,清零语句只要在函数调用语句后面即可。
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
// An highlighted block
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int n=3;
int total=0;
int a[20], b[20];
void output()
{
int i;
for (i=1; i<=n; i++)
printf("%3d", a[i]);
printf("\n");
total++;
}
//try0-try4的功能一样,但是回溯前的清零(回收现场)语句的位置不一样。一般地,清零语句只要在函数调用语句后面即可。
void try0(int k)
{
int j;
if(k>n)
output( );
else
{for(j=1; j<=n; j++)
{
if(b[j]==0)
{ a[k]=j; b[j]=1; try0(k+1); b[j]=0; }
else
continue;
}
}
}
void try2(int k)
{
int j;
if(k>n)
output( );
else
{for(j=1; j<=n; j++)
{
if(b[j]!=0)
continue;
else
{ a[k]=j; b[j]=1; try2(k+1); }
b[j]=0;
}
}
}
void try1(int k)
{
int j;
if(k>n)
output( );
else
{for(j=1; j<=n; j++)
{
if(b[j]==0)
{ a[k]=j; b[j]=1; try1(k+1); }
else
continue;
b[j]=0;
}
}
}
void try3(int k)
{
int j;
for(j=1; j<=n; j++)
{
if(b[j]==0)
{ a[k]=j; b[j]=1;
if(k<n)
try3(k+1);
else
output();
b[j]=0;
}
else
continue;
}
}
void try4(int k)
{
int j;
for(j=1; j<=n; j++)
{
if(b[j]==0)
{ a[k]=j; b[j]=1;
if(k<n)
try4(k+1);
else
output();
}
else
continue;
b[j]=0;
}
}
void try5(int k) //打印任何一个分量可以取1-n中任意值的所有排列。
{
int j;
if(k>n)
output( );
else
{for(j=1; j<=n; j++)
{
if(b[j]==0)
{ a[k]=j; b[j]=1; b[j]=0; try5(k+1); }
else
continue;
}
}
}
void try6(int k) //打印任何一个分量可以取1-n中任意值的所有排列。
{
int j;
if(k>n)
output( );
else
for(j=1; j<=n; j++)
{ a[k]=j;
try6(k+1);
}
}
int main()
{ int i;
for (i=1; i<=n; i++)
b[i]=0;
try0(1);
printf("the total number of placements for tyr0 is %3d\n", total);
try1(1);
printf("the total number of placements for tyr1 is %3d\n", total);
total=0;
try2(1);
printf("the total number of placements for tyr2 is %3d\n", total);
total=0;
try3(1);
printf("the total number of placements for tyr3 is %3d\n", total);
total=0;
try4(1);
printf("the total number of placements for tyr4 is %3d\n", total);
printf("***********************************\n");
total=0;
try5(1);
printf("the total number of placements for tyr5 is %3d\n", total);
total=0;
try6(1);
printf("the total number of placements for tyr6 is %3d\n", total);
return 0;
}