1.全排序问题
例:输出{1,2,3}的全排序
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXSIZE=11;
int count=0;
int n,P[MAXSIZE];
bool hashTable[MAXSIZE]={false};
void generateP(int index){
if(index==n+1){
for(int i=1;i<=n;i++){
printf("%d",P[i]);
}
printf("\n");
return;
}
for(int x=1;x<=n;x++){
if(hashTable[x]==false){
P[index]=x;
hashTable[x]=true;
generateP(index+1);
hashTable[x]=false;
}
}
}
int main(){
n=3;
generateP(1);
return 0;
}
2.八皇后问题
(1)暴力法:如上全排序问题,判断每一种情况是否合法
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXSIZE=10;
int P[MAXSIZE];
bool hashTable[MAXSIZE]={false};
int n;
int cnt=0;
void generateP(int index){
if(index==n+1){
bool flag=false; //判断是否互斥,即没有同行。同列,同队
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(abs(i-j)==abs(P[i]-P[j])){
flag=true;
break;
}
}
}
if(!flag) cnt++; //如果不互斥,则方案+1
return;
}
for(int x=1;x<=n;x++){
if(hashTable[x]==false){
P[index]=x;
hashTable[x]=true;
generateP(index+1);
hashTable[x]=false;
}
}
}
int main(){
n=8;
generateP(1);
printf("%d",cnt);
return 0;
}
(2)优化算法——回溯法
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXSIZE=10;
int P[MAXSIZE];
bool hashTable[MAXSIZE]={false};
int n;
int cnt=0;
void generateP(int index){
if(index==n+1){
cnt++;
return;
}
for(int x=1;x<=n;x++){
if(hashTable[x]==false){
bool flag=true;
for(int pre=1;pre<index;pre++){
if(abs(index-pre)==abs(x-P[pre])){
flag=false;
break;
}
}
if(flag){
P[index]=x;
hashTable[x]=true;
generateP(index+1);
hashTable[x]=false;
}
}
}
}
int main(){
n=8;
generateP(1);
printf("%d",cnt);
return 0;
}
总结:递归问题....开始学很简单,现在觉得好难啊,八皇后问题还是不怎么明白,理解个大概.......如果各位有啥好的理解方式,望评论见!