【洛谷 P1706】全排列问题 题解(全排列)-CSDN博客

157 阅读1分钟

全排列问题

题目描述

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

输入格式

一个整数 n n n。

输出格式

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

每个数字保留 5 5 5 个场宽。

样例 #1

样例输入 #1

3

样例输出 #1

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

提示

1 ≤ n ≤ 9 1 \leq n \leq 9 1≤n≤9。

思路

直接输出全排列。

AC代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#define AUTHOR "HEX9CF"
using namespace std;

int main()
{
    int n;
    vector<int> v;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        v.push_back(i);
    }
    do
    {
        vector<int>::iterator it = v.begin();
        for (; it != v.end(); it++)
        {
            cout << setw(5) << *it;
        }
        cout << endl;
    } while (next_permutation(v.begin(), v.end()));
    return 0;
}