LeetCode Medium: 31. 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 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进行排列组合,保证下一个比前一个大,”下一个函数”需要输入排列组合,输出下一个) 

二、思路

1)由于下一个数比上一个数大,因此需要从后往前扫描,找到递增的位置设为元素i,j(i小于j) ,这里的往前寻找的起始位置为倒数第2个,i 是当前元素,这里的递增指的是第 i 个元素小于第 j 个元素;
2)由于下一个数虽然大于上一个数,且最接近上一个数,因此找到元素 i,在i元素后面找到最接近 i 且大于i的元素 k 。由于 i 后面的元素都是降序排列的,只需要从后往前扫描找到第一个比 i 大的元素即可 
3)找到将 i 和 k 交换位置,然后将 k 后面的元素递增排序 
4)找不到,则将全部元素递增排序

三、代码

#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:])    #对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)

  参考博客: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

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8970491.html