按字典序 全排列 (xmu oj) by C++

按字典序 全排列 (xmu oj) by C++

题目描述:

描述
Generate the complete permutation of 1…N

输入
Each input file contains only one non-negative integer N (0< N < 9)

输出
Output N! Lines, according tolexicographicorder.

输入样例 1
3

输出样例 1
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

题目分析

  • 算法分析

常见的全排列问题,在算法教材上有两种算法perm1和perm2可供参考。这道题目我直接使用perm1的算法,但是书上的全排列算法无法按照字典序输出,故而加入一个对即将进行操作的部分的排序操作,加在每一次递归前,这样就解决了要按字典序输出问题。
另外需要注意的是,xmu 的 oj 这里不接受你的输出的每一行最后有空格,所以在输出函数内设置条件:输出的不是最后一个元素时才能输出空格。

  • 抄近路

另外,C++有内部库函数可以生成全排列数组,用法如下:
头文件:

#include < algorithm >

函数模板:

prev_permutation(arr, arr+size);
next_permutation(arr, arr+size);

具体用法可以参见网上其他更详细的博客

以下为完整代码:

#include <iostream>

#include <algorithm>
#define MAXINT 10
using namespace std;

int n;
int x[MAXINT];

void display(int *x){
    for (int i = 0 ; i < n ; i ++){
        cout<<x[i];
        if(i!=n-1){
            cout<<" ";
        }
    }
    cout<<"\n";
}

void Perm(int m){
    if(m == n){
        display(x);
    }
    else{
        for(int j = m ; j < n ; j ++){
            sort(x+m,x+n);
            swap(x[j],x[m]);
            Perm(m+1);
            swap(x[j],x[m]);
        }
    }
}

int main()
{
    cin>>n;
    if(n <= 0 || n > 9){
        exit(-1);
    }
    for (int i = 0 ; i < n ; i ++ ){
        x[i] = i + 1;
    }
    Perm(0);

    return 0;
}

因为我选取的角标与书上不同,所以需要注意与书上不同的角标问题。

代码截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值