您的位置:首页 > 其它

【codevs 1294】全排列

2016-07-21 22:51 260 查看
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[15];
bool b[15];
//x表示是否还有空位,当且仅当x>0时,继续放
void qpl(int x){
if(x > 0){
for(int i = 1; i <= n; i++)
if(b[i]!=0) continue;
//如果这一位上没有放数
ans[x]=i;//放上数
b[i]=1;//记录一下放上了数
qpl(x-1);//继续放数
b[i]=0;//放完数了,清空状态
}
else
for(int i = n; i >=1; i--)
printf("%d ",ans[i]);//放好了数,输出,即为一种排列
puts("");
}

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


以上
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: