codevs 1294 全排列

codevs 1294 全排列

题目描述 :
给出一个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

.
.
.

暴力枚举??!!!
想太多了
我们可是c++STL选手!!

next_permutation(start,end),和prev_permutation(start,end)。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后。

对于next_permutation函数,其函数原型为:
#include < algorithm >
bool next_permutation(iterator start,iterator end)
当当前序列不存在下一个排列时,函数返回false,否则返回true

看个例子

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
int main()
{
	int n,a[100];
	n=4;
	for(int i=1;i<=n;i++)
	{
		a[i]=i;
	}
	do
	{
		cout<<a[1]<<" "<<a[2]<<" "<<a[3]<<" "<<a[4]<<endl;
	} while(next_permutation(a+1,a+n+1));
	return 0;
}

.
.
.
.
结果是:
在这里插入图片描述
那这里要注意一个点,寻找全排列前一定要保障这个序列是一个升序序列

下面是codevs这道全排列的代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
void put(int x)  //不用输出优化是会超时嘀 
{  
    int num = 0; char c[15];
    while(x) c[++num] = (x%10)+48, x /= 10;
    while(num) putchar(c[num--]);
    putchar(' '); 
}
int main()
{
	int n;
	cin>>n;
	int a[10010];
	for(int i=1;i<=n;i++)
	{
		a[i]=i;
	}
	do
	{
		put(a[1]);
		for(int i=2;i<=n;i++)
		{
			put(a[i]);
		}
					cout<<endl;
	}while(next_permutation(a+1,a+n+1));
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值