洛谷 P1706. 全排列问题---关于next_permutation函数的使用

全排列问题

题目描述

按照字典序输出自然数 \(1\)\(n\) 所有不重复的排列,即 \(n\) 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。

输入格式

一个整数 \(n\)

输出格式

\(1 \sim n\) 组成的所有不重复的数字序列,每行一个序列。

每个数字保留 \(5\) 个场宽。

样例 #1

样例输入 #1

3

样例输出 #1

1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1

提示

\(1 \leq n \leq 9\)


题解

algorithm库中的next_permutation函数可以很好解决这类排列问题
一定要记住他的使用模板

do{
        for (int i = 1; i <= n; i ++ )
            cout << a[i] << " ";
        cout << endl;
    }while (next_permutation(a + 1, a + n + 1));

c-入门必学库函数-next_permutation-CSDN博客.png
来自 https://blog.csdn.net/weixin_52115456/article/details/127626074


如果我们需要自定义排序方式

就需要自定义一个bool函数放入next_permutation里面
如图
C-中全排列函数next_permutation-用法_nextpermutation函数-CSDN博客.png
来自 https://blog.csdn.net/howardemily/article/details/68064377


本题全排列代码

#include <bits/stdc++.h>

using namespace std;

int a[20];

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++ ) a[i] = i;
    do{
        for (int i = 1; i <= n; i ++ )
            cout << setw(5) << a[i];
        cout << endl;
    }while (next_permutation(a + 1, a + n + 1));

    return 0;
}
posted @ 2024-04-16 16:47  MsEEi  阅读(28)  评论(0)    收藏  举报