递归实现排列型枚举
题目
把 1~n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。
输入格式
一个整数n。
输出格式
按照从小到大的顺序输出所有方案,每行1个。
首先,同一行相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。
数据范围
输入样例
3
输出样例
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
题解
思路
- 每个位置有 n 种可以选择的数字:即从 1 到 n 中的任一数字
- 为保证每个数字不被重复选择,我们用 st[] 数组来记录其是否被选择
注意
- DFS 当 u == n 时,需要 return,否则会导致 Segmentation Fault
#include <iostream>
using namespace std;
const int N = 10;
int n, p[N];
bool st[N];
void dfs(int u) {
if (u == n) {
for (int i = 0; i < n; i ++) cout << p[i] << " ";
cout << endl;
return;
}
for (int i = 1; i <= n; i ++) {
if (!st[i]) {
st[i] = true;
p[u] = i;
dfs(u + 1);
st[i] = false;
}
}
}
int main () {
cin >> n;
dfs(0);
return 0;
}