Loading... 将 `1∼n` 这 `n` 个整数排成一行后随机打乱顺序,输出所有可能的次序。 ### 输入格式 一个整数 `n`。 ### 输出格式 按照从小到大的顺序输出所有方案,每行 `1` 个。 1. 同一行相邻两个数用一个空格隔开。 2. 对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。 ### 数据范围 * `1 ≤ n ≤ 9` ### 输入样例 ``` 3 ``` ### 输出样例 ``` 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 ``` ### 题目分析 DFS ### 代码实现 ``` #include <iostream> #include <bitset> #include <vector> using namespace std; const int N = 10; int n, m; bitset <N> bt; vector <int> ans; void dfs() { if (bt.count() == n) { for (const auto& i : ans) cout << i << ' '; cout << '\n'; return ; } for (int i = 1; i <= n; ++i) { if (!bt[i]) { bt[i] = 1; ans.push_back(i); dfs(); ans.erase(ans.end() - 1); bt[i] = 0; } } } int main () { ios::sync_with_stdio(0); cin.tie(0); cin >> n; dfs(); return 0; } ``` 最后修改:2023 年 09 月 23 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏