洛古P1706 全排列问题

题目描述

输出自然数1到n所有不重复的排列,即n的全排列,要求所产生的任一数字序列中不允许出现重复的数字。

输入输出格式

输入格式:

n(1≤n≤9)

输出格式:

由1~n组成的所有不重复的数字序列,每行一个序列。每个数字保留5个常宽。

输入输出样例

输入样例#1:  复制
3
输出样例#1:  复制
    1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1







在这道题内,我们可以用一个c++自带函数:什么呢?

——不告诉你

看代码吧:

#include<iostream>
#include<algorithm>
using namespace std;
int jiecheng(int n)
{
	int ans=1;
	for(int i=2;i<=n;i++)
	{
		ans*=i;
	}
	return ans;
}
int main()
{
	int n;
	cin>>n;
	int a[10001];
	for(int i=0;i<n;i++)
	{
		a[i]=i+1;
		cout<<"    "<<a[i];
	}
	cout<<endl;
	for(int i=0;i<jiecheng(n)-1;i++)
	{
		next_permutation(a,a+n);
		for(int j=0;j<n;j++)
		{
			cout<<"    "<<a[j];
		}
		cout<<endl;
	}
	return 0;
}

现在明白了吧——

next_permutation(a,a+n);

就是这行; next_permutation

next_permutation: 取出当前范围内的排列,并重新排序为下一个排列。重载版本使用自定义的比较操作。

直白点就是全排列的下一个;

好啦,现在ok了吗

猜你喜欢

转载自blog.csdn.net/zjy_code/article/details/81051935