823.排列
题目描述
给定一个整数n,将数字1~n排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数n。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1 ≤ n ≤ 9
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
难度:困难 |
---|
时/空限制:2s / 64MB |
总通过数:68 |
总尝试数:100 |
来源:语法题 |
算法标签:函数 |
AC代码
#include<stdio.h>
#include<algorithm>
using namespace std;
int n, a[10];
int main(void){
scanf("%d",&n);
for(int i = 1; i <= n; ++ i){
a[i]=i;
}
do{
for(int i = 1; i <= n; ++ i){
printf("%d ",a[i]);
}
printf("\n");
}while(next_permutation(a + 1, a + n + 1));
return 0;
}
思考和总结
在头文件里面有如下代码:
int a[];
do
{
}
while(next_permutation(a,a+n));
可产生1~n的全排列有如下代码:
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int n;
while(scanf("%d",&n)&&n){
int a[1000];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
do{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}while(next_permutation(a,a+n));
}
return 0;
}
例如输入
3
1 0 2
如果有sort()
扫描二维码关注公众号,回复:
8885153 查看本文章
输出为
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
若无
则输出为
1 0 2
1 2 0
2 0 1
2 1 0
发现函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序,在ACM International Collegiate Programming Contest, Egyptian Collegiate Programming Contest (2015) Arab Academy for Science and Technology - Alexandria, November 6th, 2015 A题就可以采用next_permutation()。
原博客:https://www.cnblogs.com/My-Sunshine/p/4985366.html
作者:静默虚空
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。