CH0303 递归实现排列型枚举

Neurocoda

Description

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

Input

一个整数 n。

Output

按照从小到大的顺序输出所有方案,每行 1 个。 首先,同一行相邻两个数用一个空格隔开。其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。

Sample Input

1
3

Sample Output

1
2
3
4
5
6
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Limit

Time LimitMemory Limit
C/C++/Rust/Pascal 1 秒,其他语言 2 秒C/C++/Rust/Pascal 32 M,其他语言 64 M

Analysis

数据范围为,在CH0301 递归实现指数型枚举 已经给出过的算法,本题规模在 3628800,大概内能完成。

Solve

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
#include <iostream>

const int N = 30;

int n, st[N];
int ans[N], idx;

void dfs(int p, int cnt) {
if(cnt == n)
for(int i = 0; i < idx; ++i)
std::cout << ans[i] << ' ';

if(cnt == n) std::cout << '\n';
for(int i = 1; i <= n; ++i) {
if(!st[i]) {
st[i] = 1;
ans[idx++] = i;
dfs(i, cnt + 1);
st[i] = 0;
--idx;
}
}
}

int main () {
std::ios::sync_with_stdio(0);
std::cin.tie(0);

std::cin >> n;
for(int i = 1; i <= n; ++i) {
st[i] = 1;
ans[idx++] = i;
dfs(i, 1);
st[i] = 0;
--idx;
}
}

Ref

  • Title: CH0303 递归实现排列型枚举
  • Author: Neurocoda
  • Created at : 2026-09-29 16:39:39
  • Updated at : 2026-09-29 16:49:32
  • Link: https://neurocoda.com/p/9863ef22.html
  • License: This work is licensed under CC BY-ND 4.0.
On this page
CH0303 递归实现排列型枚举