这个程序里有递归,分治算法和散列算法,散列算法我在上上篇讲过,有兴趣的可以看看。
实现123的全排列。
以下 程序建议使用VC实现,DEV还得自己定义bool函数。
#include <stdlib.h>
#include <cstdio>
const int maxn=11;
bool hashTable[maxn]={false};
int n,p[maxn];//全局变量
void generatep(int index)
{
int i,x;
if(index==n+1)
{
for(i=1;i<=n;i++)
{
printf("%d",p[i]);
}
printf("\t");
return;
}
for(x=1;x<=n;x++)
{
if(hashTable[x]==false)
{
p[index]=x;
hashTable[x]=true;
generatep(index+1);
hashTable[x]=false;
}
}
}
int main(void)
{
n=3;
generatep(1);
return 0;
}
这个程序就是一直调用自己,不过难的地方就是很容易把自己转迷糊,类似二叉树那种,程序我也是只搞懂80%,也有不是很明白的地方,希望完全懂此程序的热心的小伙伴能给我讲讲,万分感谢!!!