目录
1.全排列
#include<cstdio>
#include<vector>
#include<cstring>
#include<string>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=100010;
int martix[maxn];
int hashtable[maxn]={0};
int n;
void print(int index){
if(index==n+1){
for(int i=1;i<=n;i++){
printf("%d",martix[i]);
}
printf("\n");
}else{
for(int i=1;i<=n;i++){
if(hashtable[i]==0){
martix[index]=i;
hashtable[i]=1;
print(index+1);
hashtable[i]=0;
}
}
}
}
int main(){
n;
scanf("%d",&n);
//从1开始输出到n的全排列
print(1);
return 0;
}
2.八皇后(回溯)
#include<cstdio>
#include<vector>
#include<cstring>
#include<string>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
int martix[100];
int hashtable[100]={0};
int n;
int counts=0;
void print(int index){
if(index==n+1){
counts++;
}else{
for(int col=1;col<=n;col++){
if(hashtable[col]==0){
bool flag=true;
for(int pre=1;pre<index;pre++){
if(abs(pre-index)==abs(martix[pre]-col)){
flag=false;
}
}
if(flag){
martix[index]=col;
hashtable[col]=1;
print(index+1);
hashtable[col]=0;
}
}
}
}
}
int main(){
scanf("%d",&n);
print(1);
printf("%d",counts);
}