【算法代码一:dfs】
dfs算法常表现为复杂的递归函数形式,因此掌握递归是理解dfs算法的基础。
dfs算法的模板如下:
void dfs(int step) {
判断边界 {
输出解
}
尝试每一种可能 {
满足check条件{
标记
继续下一步:dfs(step+1)
恢复初始状态(回溯的时候要用到)
}
}
}
全排列的 dfs 实现的代码如下所示:
#include <bits/stdc++.h>
using namespace std;
const int maxn=10;
int a[maxn];
int book[maxn];
int n;
void dfs(int step){
if(step==n+1){
for(int i=1;i<=n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return;
}
for(int i=1;i<=n;i++){
if(book[i]==0){
a[step]=i;
book[i]=1;
dfs(step+1);
book[i]=0;
}
}
return;
}
int main() {
cin>>n;
dfs(1);
return 0;
}
【算法代码二:next_permutation()】
在使用 next_permutation() 的时候,初始序列一般是一个字典序最小的序列。
如果不是,可以用 sort() 排序,得到最小序列,然后再使用 next_permutation()。
全排列的 next_permutation() 实现的代码如下所示:
#include <bits/stdc++.h>
using namespace std;
const int maxn=100;
int a[maxn];
int n;
int main() {
cin>>n;
for(int i=1; i<=n; i++) a[i]=i;
sort(a+1,a+1+n);
do {
for(int i=1; i<=n; i++) cout<<a[i]<<" ";
cout<<endl;
} while(next_permutation(a+1,a+1+n));
return 0;
}
/*
in:
3
out:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/134226708
https://blog.csdn.net/hnjzsyjyj/article/details/134347639
https://blog.csdn.net/hnjzsyjyj/article/details/118613417