C++库函数之next_permutation()全排列函数

next_permutation()函数

next_permutation()函数包含在里面

其函数原型为为:

#include<algorithm>
bool next_permautation(iterator start, iterator end);

当前序列不存在下一个排列时,函数返回false,否则返回true.

使用基本格式为:

int a[];
do{

}while(next_permutation(a,a+n));

另外需要强调的是,next_permutation()在使用时在使用前需要对待排列数组进行升序排序,否则只能找出该序列之后的全排列数

先写个例子

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

int main()
{
    int n,a[1000];
    cin >> n;
    for(int i = 0 ; i < n ; i++)
        cin >> a[i];
    
    do{
        for(int i = 0 ; i < n ; i++)
            cout << a[i] << " ";
        cout << endl;
    }while(next_permutation(a, a + n));
    return 0;
}

在这里插入图片描述
但是有些数据则得不到想要的结果,例如
在这里插入图片描述
很显然这里面少了一些组合,即0 4 2,0 2 4
next_permutation()函数是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。所以排列前要先考虑对待排数列进行排序

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

int main()
{
    int n,a[1000];
    cin >> n;
    for(int i = 0 ; i < n ; i++)
        cin >> a[i];
    sort(a,a + n);//进行sort排序,即将待排数列变为升序
    do{
        for(int i = 0 ; i < n ; i++)
            cout << a[i] << " ";
        cout << endl;
    }while(next_permutation(a, a + n));
    return 0;
}

这时问题便解决了
在这里插入图片描述

prev_permutation()函数

prev_permutation()函数将[start,end]区间中的序列转换为字典序的上一个排列。如果上一个排列存在返回true,如果上一个排列不存在(即区间中包含的是字典序的第一个排列),则该函数返回false,并将区间转换为字典序的最后一个排列。
所以在用prev_permutation()函数时要对序列进行降序排列

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

int main()
{
    int n,a[1000];
    cin >> n;
    for(int i = 0 ; i < n ; i++)
        cin >> a[i];
    sort(a,a + n,greater<int>());//进行sort排序,greater<int>()即将待排数列变为降序
    do{
        for(int i = 0 ; i < n ; i++)
            cout << a[i] << " ";
        cout << endl;
    }while(prev_permutation(a, a + n));
    return 0;
}

在这里插入图片描述

总结

next_permutation指下一个排列,prev_permutation指前一个排列
next_permutation在进行全排列时必须保证待排序数组升序,这样才能得到全部n!种排列方式。
同理prev_permutation在进行全排列时必须保证待排序数组降序,这样才能得到全部n!种排列方式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值