洛谷 P1706 全排列

可能是最简单的题了……讲真搜索hhh

洛谷

 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

 搜索版:

//setw(5)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<iomanip>
using namespace std;

int n,a[520]= {0}; //数组记录多种情况
bool b[521]= {0};

int print() {
    for(int k=1; k<=n; k++)cout<<setw(5)<<a[k];
    printf("
");
}

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

int main() {
    cin>>n;
    search(1);
    return 0;
}

栈版:

#include <iostream>
#include <cstdio>
using namespace std;

int n;
int stack[10],used[10];

void dfs() {
    int top=1;
    stack[top]=0;
    while(top>=1) {
        if(top==n+1) {
            for(int i=1; i<=n; ++i)
                printf("%5d",stack[i]);
            printf("
");
            used[stack[--top]]=false;
            continue;
        }
        do {
            stack[top]++;
        }while(used[stack[top]] && stack[top]<=n);
        if(stack[top]<=n) {
            used[stack[top]]=true;
            stack[++top]=0;
        }
        else
            used[stack[--top]]=false;
    }
}

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

如果运气好也是错,那我倒愿意错上加错!

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

原文地址:https://www.cnblogs.com/zxqxwnngztxx/p/6612942.html