AcWing 94. 递归实现排列型枚举
宋标 Lv5

题目

个整数排成一行后随机打乱顺序,输出所有可能的次序。

输入格式

一个整数

输出格式

按照从小到大的顺序输出所有方案,每行 个。

首先,同一行相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。

数据范围

输入样例:

3

输出样例:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

const int N = 15;

int n;

bool st[N];
int c[N];

void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; ++ i) printf("%d ", c[i]);
puts("");
return;
}

for (int i = 1; i <= n; ++ i)
if (!st[i])
{
c[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}

int main()
{
cin >> n;

dfs(0);

return 0;
}
 评论