全排列next_permutation函数

概述

STL提供了两个用来计算排列组合关系的算法,分别是next_permutation(“下一个”排列组合)和prev_permutation(“前一个”排列组合)。两者都位于#include < algorithm >中。
next_permutation:把两个迭代器(或指针)指定的部分看作一个排列,求出这些元素构成的全排列中,字典序排在下一个的排列,并直接在序列上更新。另外,若不纯在排名更靠前的排列,则返回false,否则返回true。
prev_permutation:同理与next_permutation,求出这些元素构成的全排列中,字典序排在前一个的排列。

使用方式

do
{
    ...   
} while (next_permutation(a, a + n));//prev_permutation类似

若想实现全排列,首先把数组先排序,因为next_permutation是找“下一个”排列组合。所以先将数组从小到大排序。

#include <iostream>
#include <algorithm>

using namespace std;
typedef long long ll;
int main()
{
    int a[100];
    for (int i = 1; i <= 3; i++)
        a[i] = i;
    sort(a + 1, a + 3 + 1);
    do
    {
        for (int i = 1; i <= 3; i++)
            cout << a[i] << " ";
        cout << endl;
    } while (next_permutation(a + 1, a + 3 + 1));
    return 0;
}

/*
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/

如果我们上述代码使用的是prev_permutation,输出结果只有1 2 3;把数组从大到小排序,输出结果也只有3 2 1。

应用例子

输出一个数组中第k个全排列的序列,也就比较容易了:

int k = 0;
do
{
    k++;
    if (k == 1)
    {
        for (int i = 1; i <= 3; i++)
            cout << a[i] << " ";
        cout << endl;
    }
} while (next_permutation(a + 1, a + 3 + 1));

或输出任意一个字符串的字典序的全排列:

#include <iostream>
#include <algorithm>

using namespace std;
typedef long long ll;
int main()
{
    string s = "bac";
    sort(s.begin(), s.end());
    do
    {
        cout << s << endl;
    } while (next_permutation(s.begin(), s.end()));
    return 0;
}
/*
输出:
abc
acb
bac
bca
cab
cba
*/

参考链接:原文链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值