top1编程
← 返回题目
题解

全排列问题

1 条题解

  • 0
    @ 2026-10-20 23:26:36

    1. 解题思路

    从升序排列开始,输出当前排列后不断调用next_permutation获取字典序下一个排列。

    **关键规则:**每个整数都用setw(5)指定场宽;必须先输出初始升序排列。

    2. 坑点和注意事项

    • 数据范围:1≤n≤9。
    • 每个整数都用setw(5)指定场宽;必须先输出初始升序排列。
    • 最多9!=362880行;输出本身需要n×n!次整数操作。

    3. 复杂度

    • **时间复杂度:**O(n×n!)。
    • **空间复杂度:**O(n)。
    /*
    思路:从升序排列开始,输出当前排列后不断调用next_permutation获取字典序下一个排列。
    关键规则:每个整数都用setw(5)指定场宽;必须先输出初始升序排列。
    数据范围:1≤n≤9;注意数组下标和中间运算的数据类型。
    时间复杂度:O(n×n!);空间复杂度:O(n)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        int a[10];
        // 全排列问题:每个整数都用setw(5)指定场宽;必须先输出初始升序排列。
        for (int i = 0; i < n; i++)
            a[i] = i + 1;
        do
        {
            for (int i = 0; i < n; i++)
                cout << setw(5) << a[i];
            cout << '\n';
        } while (next_permutation(a, a + n));
    }
    
    • 1