C++ STL next_permutation and prev_permutation introduction

我们经常会遇到这样的问题。
example:我们有三个数 1 2 3,要求输出他们的全排列并按照字典序的顺序。
            123
            132
            213
            231
            312
            321
通常的做法是写个函数然后递归解决。
这次我来介绍两个函数 next_permutation 和 prev_permutation
next_permutation是求出当前排列的下一个排列,它的返回值是0或1
它需要两个参数,第一个是起始地址,第二个是结束地址。 next_permutation(a, a+n);
比如现在是123 用一次 next_permutation就变成了,返回值是1
如果是321了,因为没有下一个返回值就是0

同理 prev_permutation是求出当前排列的上一个排列,返回值也是0或1

code:

#include <iostream>
#include <algorithm>
using namespace std;

bool cmp1(int a, int b)
{
    if(a < b)
        return 1;
    return 0;
}
bool cmp2(int a, int b)
{
    if(a > b)
        return 1;
    return 0;
}

int main()
{
    int a[100];
    for(int i=0; i<3; i++)
    {
        cin >> a[i];
    }
    sort(a, a+3, cmp1);     // 先排序成从小到大
    do{
        for(int i=0; i<3; i++)
            cout << a[i];
        cout << endl;
    }while(next_permutation(a, a+3));
    cout << endl;
    sort(a, a+3, cmp2);
    do{
        for(int i=0; i<3; i++)
            cout << a[i];
        cout << endl;
    }while(prev_permutation(a, a+3));



    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值