AcWing0842 排列型枚举
给定一个整数 n,将数字 1∼n 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数 n 。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1 ≤ n ≤ 7
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
算法1 - DFS枚举(22 ms):
#include <iostream>
using namespace std;
const int N = 8;
// selected[i] = 1 表示 i 已选择
// comb[1..idx] 记录已经排序的组合数
bool selected[N];
int comb[N], n;
void DFSArrange(int idx) {
// 若全部已选,则打印
if (idx > n) {
for (int i = 1; i <= n; ++i) {
cout << comb[i] << " ";
}
cout << endl;
}
// 处理数字 idx
for (int i = 1; i <= n; ++i) {
// 找到第一个未选择的数字
if (!selected[i]) {
// 选择 i
selected[i] = true;
comb[idx] = i;
DFSArrange(idx + 1);
// 不选 i
selected[i] = false;
}
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
// idx 指向数字 i 在当前组合数字中的排列位置
int idx = 1;
cin >> n;
DFSArrange(idx);
return 0;
}
算法2 - 状态压缩(20 ms):
与算法 1 基本一致,区别在于使用一个 int state
中的二进制位 $b_0,b_1,…,b_{n-1}$ 代替数字的状态数组 selected[1..n]
。
#include <iostream>
using namespace std;
const int N = 7;
int n, comb[N + 1];
void DFS(int idx) {
if (idx > n) {
for (int i = 1; i <= n; ++i) {
cout << comb[i] << " ";
}
cout << endl;
}
for (int i = 0; i < n; ++i) {
if (!(state >> i & 1)) {
state += 1 << i;
comb[idx] = i + 1;
DFS(idx + 1);
state -= 1 << i;
}
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n;
int idx = 1;
DFS(idx);
return 0;
}