洛谷 P1706 全排列问题

题目链接

https://www.luogu.org/problemnew/show/P1706


题目描述

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


输入输出格式

输入格式:
n(1≤n≤9)

输出格式:
由1~n组成的所有不重复的数字序列,每行一个序列。每个数字保留5个常宽。


输入输出样例

输入样例#1:
3
输出样例#1:
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;

bool b[10086];
int a[10086];
int n,m;
long long tot;

void print() {
    for(int i=1; i<=n; i++) {
        cout<<setw(5)<<a[i];
    }
    cout<<endl;
}

int search(int t) {
    for(int i=1; i<=n; i++) {
        if(!b[i]) {
            a[t]=i;
            b[i]=1;
            if(t==n) {
                print();
            } else search(t+1);
            b[i]=0;
        }
    }
}


int main() {
    scanf("%d",&n);
    search(1);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/loceaner/p/10712905.html