【codevs 1294】全排列

来源:互联网 发布:333什么意思网络用语 编辑:程序博客网 时间:2024/04/30 07:47

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

想象一下,有n个可以放数的空位
每放一个就继续放下一个直到没有空位,回溯
记录每次放满
即为全排列⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄

#include <iostream>#include <cstdio>#include <algorithm>using namespace std;int n,ans[11];bool b[11];//x表示是否还有空位,当且仅当x>0时,继续放void qpl(int x){    if(x > 0)    {        for(int i = 1; i <= n; i++)        if(b[i]==0)//如果这一位上没有放数        {            ans[x]=i;//放上数            b[i]=1;//记录一下放上了数            qpl(x-1);//继续放数            b[i]=0;//放完数了,清空状态        }    }    else        for(int i = n; i >=1; i--)            printf("%d ",ans[i]);//放好了数,输出,即为一种排列        printf("\n");}int main(){    scanf("%d",&n);    qpl(n);    return 0;}

以上

0 0