https://www.luogu.com.cn/problem/P1706
这道题也可以用STL中
next_permutation
函数
关于next_permutation函数的文章 https://blog.csdn.net/qian2213762498/article/details/79683905?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2.pc_relevant_antiscanv2&utm_relevant_index=5
该函数头文件为#include<algorithm>
简要介绍一下next_permutation
函数的功能
next_permutation()
函数功能是输出所有比当前排列大的排列,顺序是从小到大。当排列已经是最大,返回假,否则真。
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n;
cin >> n;
for(int i = 1; i<= n; i++) {
a[i] = i;
}
do {
for(int i = 1; i <= n; i++) {
cout << " " <<a[i];
}
cout << endl;
}while(next_permutation(a + 1, a + n + 1));
return 0;
}
dfs深搜
#include<iostream>
using namespace std;
const int N = 15;
int n;
int a[N];
bool st[N];
void dfs(int u)
{
if(u > n)
{
for(int i = 1; i <= n; i ++)
printf("%5d", a[i]);
puts("");
return;
}
for(int i = 1; i <= n; i ++)
{
if(!st[i])
{
a[u] = i;
st[i] = true;
dfs(u + 1);
a[u] = 0;
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(1);
return 0;
}