31. Next Permutation

Description

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

Solution

求一个排列的下一个排列,medium,比如对于排列(6,3,7,2,8,8,5,4,1),从后往前找完整的降序列,直到index=4,即8>2,此时交换2和尾部升序列中>2的第一个数4,得到(6,3,7,4,8,8,5,2,1),对于尾部的降序列进行reverse即得到下一个排列

void nextPermutation(vector<int>& nums) {
    int topIndex = nums.size() - 1;
    while (topIndex > 0 && nums[topIndex] <= nums[topIndex - 1]) {
        topIndex--;
    }
    if (topIndex == 0) {//如果是全部降序,即最大排列,返回升序列
        std::reverse(nums.begin(), nums.end());
        return ;
    }
    int swapIndex = nums.size() - 1;
    while (nums[swapIndex] <= nums[topIndex - 1]) {
        swapIndex--;
    }
    swap(nums[topIndex - 1], nums[swapIndex]);
    std::reverse(nums.begin() + topIndex, nums.end());
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容