Middle-题目88:31. Next Permutation

本文介绍了一个数组求下一个字典序排列的方法,通过C++标准库函数next_permutation实现。文章详细解析了next_permutation的源码及其实现原理,帮助读者理解如何就地替换数组以获得下一个更大的排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原文:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
题目大意:
求出一个数组的下一个字典序的排序结果。
题目分析:
使用C++中的库函数next_permutation实现(在头文件algorithm中)。
函数接口:bool next_permutation( iterator start, iterator end);
即求start-end这个序列的下一个排序。
源码:(language:cpp)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        next_permutation(nums.begin(), nums.end());
    }
};

成绩:
12ms,beats 10.04%,众数12ms,88.95%
Cmershen的碎碎念:
C++11中,Next_permutation的源码如下:

    bool _Next_permutation(_BidIt _First, _BidIt _Last, _Pr _Pred)
    {   // permute and test for pure ascending, using _Pred
    _BidIt _Next = _Last;
    if (_First == _Last || _First == --_Next)
        return (false);

    for (; ; )
        {   // find rightmost element smaller than successor
        _BidIt _Next1 = _Next;
        if (_DEBUG_LT_PRED(_Pred, *--_Next, *_Next1))
            {   // swap with rightmost element that's smaller, flip suffix
            _BidIt _Mid = _Last;
            for (; !_DEBUG_LT_PRED(_Pred, *_Next, *--_Mid); )
                ;
            _STD iter_swap(_Next, _Mid);
            _STD reverse(_Next1, _Last);
            return (true);
            }

        if (_Next == _First)
            {   // pure descending, flip all
            _STD reverse(_First, _Last);
            return (false);
            }
        }
    }

大致思路:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元素颠倒排序,即求出下一个序列了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值