You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.2 KiB

2 years ago
##[$AcWing$ $842$. 排列数字](https://www.acwing.com/problem/content/description/844/)
### 一、题目描述
给定一个整数 $n$,将数字 $1n$ 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
**输入格式**
共一行,包含一个整数 $n$。
**输出格式**
按字典序输出所有排列方案,每个方案占一行。
**数据范围**
$1≤n≤7$
**输入样例:**
```cpp {.line-numbers}
3
```
**输出样例:**
```cpp {.line-numbers}
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
```
### 二、实现代码
```cpp {.line-numbers}
#include <bits/stdc++.h>
using namespace std;
const int N = 10;
int n;
int a[N], al;
bool st[N];
void dfs(int u) {
// 如果到达了终点
if (u == n + 1) {
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
puts("");
return;
}
for (int i = 1; i <= n; i++)
if (!st[i]) {
a[al++] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
al--;
}
}
int main() {
cin >> n;
// 开始
dfs(1);
return 0;
}
```