【题目来源】
https://www.luogu.com.cn/problem/P1706
【题目描述】
按照字典序输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
【输入格式】
一个整数 n。
【输出格式】
由 1∼n 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 5 个场宽。
【输入样例】
3
【输出样例】
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
【说明/提示】
1≤n≤9。
【算法分析】
● 该算法是理解回溯算法的经典案例,常用于解决排列组合相关问题。
● 题目要求保留 5 个场宽,可通过命令 printf("%5d", x); 实现。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=10;
int a[maxn],st[maxn];
int n;
void dfs(int step) {
if(step==n+1) {
for(int i=1; i<=n; i++) {
printf("%5d",a[i]);
}
printf("\n");
return;
}
for(int i=1; i<=n; i++) {
if(st[i]==0) {
a[step]=i;
st[i]=1;
dfs(step+1);
st[i]=0;
}
}
return;
}
int main() {
scanf("%d",&n);
dfs(1);
return 0;
}
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/119255867
https://www.luogu.com.cn/problem/solution/P1706