谁能帮我解释下这段全排列算法

来源:百度知道 编辑:UC知道 时间:2024/06/22 10:12:07
void perm(char *list, int i, int n){
int j,temp;
if(i == n){
for(j = 0; j < n; j++)
cout<<list[j];
cout<<" ";
}
else{
for(j = i; j < n; j++){
SWAP(list[i],list[j],temp);
perm(list,i+1,n);
SWAP(list[i],list[j],temp);

}

}
}
出使的i = 0;
最好具体点
比如举n = 3时, 递归是怎么递归的
在其中i是怎么变化的,数组里面元素是怎么交换的
这段排序算法是肯定没问题的,我已经运行过了,所以不用找其中的错误

原理大概如下:

首先依次从i个数字挑出一个数字作为第一个数字,将其余i-1数字作全排列,执行i次之后就生成所有的全排列了

其余i-1数字作全排列的做法可效仿i个数字的做法

for(j = i; j < n; j++){
SWAP(list[i],list[j],temp); //将第j数字做为第一个
perm(list,i+1,n);
SWAP(list[i],list[j],temp); //将第j数字换回原来位置,准备用第j+1个做做为第一个

}
-----------------------------------------------------------
建议你将函数修改成以下形式,自己观察一下
-----------------------------------------------------------
void perm(char *list, int i, int n){
int j,temp;
for(j = 0; j < n; j++)
cout<<list[j]<<endl;
if(i == n){
for(j = 0; j < n; j++)
cout<<list[j];
cout<<" "<<i=n了<<" ";
}
else{
for(j = i; j < n; j++){
SWAP(list[i],list[j],temp);
perm(list,i+1,n);
SWAP(list[i],list[j],temp);

}

}
}

hanoi程序知道吗?就是汉诺塔
运用的递归调用
原理:
把N个东西从第一个柱子搬到第三个柱子
如果可以有人把第一个柱子上的N-1块搬到