You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

##AcWing 842. 排列数字

一、题目描述

给定一个整数 n,将数字 1n 排成一排,将会有很多种排列方法。

现在,请你按照字典序将所有的排列方法输出。

输入格式 共一行,包含一个整数 n

输出格式 按字典序输出所有排列方案,每个方案占一行。

数据范围 1≤n≤7

输入样例:

3

输出样例:

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

二、实现代码

#include <bits/stdc++.h>

using namespace std;
const int N = 10;
int n;
int a[N], al;
bool st[N];

void dfs(int u) {
    // 如果到达了终点
    if (u == n + 1) {
        for (int i = 0; i < n; i++)
            printf("%d ", a[i]);
        puts("");
        return;
    }
    for (int i = 1; i <= n; i++)
        if (!st[i]) {
            a[al++] = i;
            st[i] = true;
            dfs(u + 1);
            st[i] = false;
            al--;
        }
}

int main() {
    cin >> n;
    // 开始
    dfs(1);
    return 0;
}