LeetCode Medium: 31. Next Permutation

1. The topic

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 and use only constant 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

字典序排序生成算法,大致意思就是给定一个序列,生成下一个比之大的序列,若已经是最大的,则返回最小的,例如:123-132-213-231-312-321(将123进行排列组合,保证下一个比前一个大,”下一个函数”需要输入排列组合,输出下一个) 

2. Ideas

1) Since the next number is larger than the previous number, it is necessary to scan from the back to the front to find the incremented position as the element i, j (i is less than j), and the starting position of the forward search here is the penultimate second , i is the current element, the increment here means that the i-th element is less than the j-th element;
2) Since the next number is greater than the previous number and is the closest to the previous number, find element i, after the i element Find the element k closest to i and greater than i. Since the elements after i are arranged in descending order, you only need to scan from the back to the front to find the first element larger than i 
3) Find the exchange position of i and k, and then sort the elements after k in ascending order 
4) Find If not, sort all elements in ascending order

3. Code

#coding:utf-8
def nextPermutation(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    if len(nums) <= 1:
        return
    for i in range(len(nums) - 2, -1, -1):
        if nums[i] < nums[i + 1]:
            for k in range(len(nums) - 1, i, -1):
                if nums[k] > nums[i]:
                    nums[i], nums[k] = nums[k], nums[i]
                    nums[i + 1:] = sorted(nums[i + 1:]) # sort the elements after i
                    break
            break
        else:
            if i == 0:
                nums.sort()
    print(nums)
    return nums
if __name__ == '__main__':
    nums = [2,7,6,3,5,4,1]
    nextPermutation(nums)

  Reference blog: https://blog.csdn.net/qq_28119401/article/details/52972616 https://www.cnblogs.com/mydesky2012/p/5620006.html https://blog.csdn.net/nomasp/article /details/49913627 https://www.cnblogs.com/zhang-hill/p/5067057.html https://blog.csdn.net/ljiabin/article/details/44943881

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325031363&siteId=291194637