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

数据范围及提示 Data Size & Hint
 

分类标签 Tags 点此展开 

 
 
AC代码:
1、系统栈dfs
O(2^(n+1)-1)
#include<cstdio>
using namespace std;
const int N=110;
int n,vis[N],a[N];
void dfs(int x){
    if(x==n+1){
        for(int i=1;i<=n;i++){
            putchar(a[i]+'0');putchar(' ');
        }
        putchar('
');
        return ;
    }
    for(int i=1;i<=n;i++){
        if(!vis[i]){
            vis[i]=1;
            a[x]=i;
            dfs(x+1);
            vis[i]=0;
        }
    }
}
int main(){
    scanf("%d",&n);
    dfs(1);
    return 0;
}

2、手工栈dfs

O(2^(n+1)-1)

#include<cstdio>
using namespace std;
const int N=1100;int n;
void dfs(){
    int top,a[N],vis[N]={0};
    a[top=1]=0;
    while(top>=1){
        if(top==n+1){
            for(int i=1;i<=n;i++){
                putchar(a[i]+'0');putchar(' ');
            }
            putchar('
');vis[a[--top]]=0;
            continue;
        }
        do
            a[top]++;
        while(vis[a[top]]&&a[top]<=n);
        if(a[top]<=n)
            vis[a[top]]=1,a[++top]=0;
        else
            vis[a[--top]]=0;
    }
}
int main(){
    scanf("%d",&n);
    dfs();
    return 0;
}

3、stl

O(n!)

#include<cstdio>
#include<algorithm>
using namespace std;
int a[15],n;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++) a[i]=i;
    do{
        for(int i=1;i<=n;i++){
            putchar(a[i]+'0');putchar(' ');
        }
        putchar('
');
    }while(next_permutation(a+1,a+n+1));
    return 0;
} 

手写O(n!)//无序排列,没有AC

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int N=11000;
int n,s[N];
void dfs(int x){
    if(x==n+1){
        for(int i=1;i<=n;i++){
            printf("%d ",s[i]);
        }
        putchar('
');
        return ;
    }
    for(int i=x;i<=n;i++){
        swap(s[x],s[i]); 
        dfs(x+1);
        swap(s[x],s[i]);
    }
        
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++) s[i]=i;
    dfs(1);
    return 0;
}

(思想来自http://wuchong.me/blog/2014/07/28/permutation-and-combination-realize/)

思路挺好,代码实现就~~代码不对,待调

原文地址:https://www.cnblogs.com/shenben/p/5679123.html