P1706 全排列问题——回溯、暴力枚举

题目描述

按照字典序输出自然数 \(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\)

题解

#include <bits/stdc++.h>
using namespace std;
int n;
vector<vector<int>> solutions;
vector<int> mycurrent;
vector<bool> used;
void func() {
    if(mycurrent.size()==n) {
        solutions.push_back(mycurrent);
        return;
    }
    for(int i=1;i<=n;i++) {
        if(!used[i]) {
            mycurrent.push_back(i);
            used[i]=true;
            func();
            used[i]=false;
            mycurrent.pop_back();
        }
    }
}
int main() {
    cin>>n;
    used.resize(n+1);
    func();
    for (const auto& solution:solutions) {
        for (int num:solution) {
            cout<< setw(5) << num;
        }
        cout<<endl;
    }
}
posted @ 2025-02-16 21:55  ToFuture$  阅读(27)  评论(0)    收藏  举报