1 条题解
-
0
练57.1 全排列问题
解题思路
初始升序排列1~n,先输出当前排列,再用next_permutation生成下一个,直到返回false。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
初始排列必须输出;每个数字宽度5。
复杂度
输出n!个排列,时间O(n·n!),空间O(n)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); iota(a.begin(), a.end(), 1); do { for (int x : a) cout << setw(5) << x; cout << "\n"; } while (next_permutation(a.begin(), a.end())); return 0; }
- 1