C++ STL中 next_permutation函数

本文详细介绍了C++标准库STL中的next_permutation函数,用于生成序列的下一个排列。全排列概念、函数用法及复杂度分析一并阐述。示例代码演示了如何使用next_permutation生成字符串的所有排列,并展示了与prev_permutation和lexicographical_compare等函数的关联。
摘要由CSDN通过智能技术生成

STL提供求下一个排列组合函数next_permutation(),该函数被定义于头文件algorithm。

全排列定义: 从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
公式: 全排列数f(n)=n!(定义0!=1)

函数next_permutation()的定义有两种形式:

//第一种
template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
//第二种
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );
//第一个种使用<来确定顺序,而第二个种则使用 comp比较对象。
//第二种方法中的第三个参数为比较函数对象

复杂度: O(n)

排列范围: [first,last),包括first,不包括last。

返回值:如果没有下一个排列组合,返回false,否则返+回true。

每执行next_permutation()一次,就会把新的排列放到原来的空间里。

注意:

在使用next_permutation()的时候,初始序列一般是一个字典序最小的序列,如果不是,可以使用sort()排序,
得到最小序列,然后再使用next_permutation()。

next_permutation的一种实现方法:

template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;

    while (true) {
        BidirIt i1, i2;

        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

使用方法:

#include <algorithm>
#include <string>
#include <iostream>
 
int main()
{
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << '\n';
    } while(std::next_permutation(s.begin(), s.end()));
}

输出:

aab
aba
baa

与next_permutation()相关函数:

         1. prev_permutation():求前一个排列组合
         2. 2. lexicographical_compare():字典比较

实现方法,使用方法
全排列简介
练习-排列式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GT-一二

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值