LeetCode 31. Next Permutation

本文提供了一个关于LeetCode上‘下一个排列’问题的有效解决方案。该算法从数组末尾开始向前查找,找到第一个可以与后面较大数值交换的位置,并将之后的数组进行升序排序,实现寻找下一个字典序排列。

Problem:

https://leetcode.com/problems/next-permutation/

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

Thought:

  from end to begin, find the first number that have number greater than it after, then swap the number with the minimum greater number, the sort the array after the number.

  e.g    2 6 3 4 3 1     find  arr[2] = 3, the swap it with arr[3] = 4, sort arr[3] to arr[5]

 

Code  C++:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() <= 1)
            return;
        
        for (int i = nums.size() - 2; i >= 0; i--) {
            int greater_min = i;//greater_min point to the minimum number greater than nums[i]
            
            for (int j = nums.size() - 1; j > i; j--) {//get greater_min
                if (nums[j] > nums[i]) {
                    if (greater_min == i) {
                        greater_min = j;
                        continue;
                    }
                    greater_min  = nums[j] < nums[greater_min] ? j : greater_min;
                }
            }
            
            if (greater_min != i) {
                swap(nums[i], nums[greater_min]);
                sort(nums.begin() + i + 1, nums.end());
                return;
            }
        }
        sort(nums.begin(), nums.end());
        return;
    }
};

 

转载于:https://www.cnblogs.com/gavinxing/p/5532720.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值