CODE[VS] 1294 全排列

1294 全排列

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
 
 
题目描述 Description

给出一个n, 请输出n的所有全排列

输入描述 Input Description

读入仅一个整数n   (1<=n<=10)

输出描述 Output Description

一共n!行,每行n个用空格隔开的数,表示n的一个全排列。并且按全排列的字典序输出。

样例输入 Sample Input

3

样例输出 Sample Output

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

这个题目个人是用深搜解决的,貌似用STL的话就很简单了

就是先搜索那个数放第一,再递归放后面的数

这题目竟然卡了printf,scanf,我还能说什么

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int visit[11];
int b[11];
int n;
void dfs(int i)
{
    if(i>n)
    {
        for(int j=1;j<=n;j++)
        {
            if(j!=n)
                printf("%d ",b[j]);
            else printf("%d
",b[j]);
        }
        return;
    }
    else
    {
        for(int j=1;j<=n;j++)
        {
            if(!visit[j])
            {
                b[i] = j;
                visit[j] = 1;
                dfs(i+1);
                visit[j] = 0;
            }
        }
    }
}
int main()
{
    scanf("%d",&n);
    memset(visit,0,sizeof(visit));
    dfs(1);
    return 0;
}
彼时当年少,莫负好时光。
原文地址:https://www.cnblogs.com/l609929321/p/6576900.html