> 文章列表 > 洛谷 P1706 全排列问题

洛谷 P1706 全排列问题

洛谷 P1706 全排列问题

题目描述

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

输入格式

一个整数 n。

输出格式

由 1∼n 组成的所有不重复的数字序列,每行一个序列。

每个数字保留 55 个场宽。

输入输出样例

输入 #1复制

3

输出 #1

    1    2    31    3    22    1    32    3    13    1    23    2    1

说明/提示

1≤n≤9。

题目分析: 

主要用到algorithm 里面的 next_permutation函数

(next_permutation函数是 STL 中的一种函数,它可以生成序列的下一个排列。如果当前排列是最后一个排列,next_permutation函数会返回false。这个函数有两种使用方式,一种是不带参数,另一种是带一个比较函数作为参数。)

Ac代码:

#include<bits/stdc++.h>
using namespace std;
int a[10];
int main()
{long long mul=1;int n;cin >> n;for (int i = 2; i <= n; i++){mul *= i;}for (int i = 0; i < n; i++){a[i] = i+1;}printf("    ");for (int i = 0; i < n; i++){cout << a[i];if (i != n - 1) cout << "    ";}cout << endl;for (int i = 0; i <mul-1 ; i++){next_permutation(a, a + n);printf("    ");for (int i = 0; i < n; i++){cout << a[i];if(i!=n-1) cout<< "    ";}cout << endl;}
}