dfs 之 下一个排列

52. 下一个排列

中文English

给定一个整数数组来表示排列,找出其之后的一个排列。

Example

例1:

输入:[1]
输出:[1]

例2:

输入:[1,3,2,3]
输出:[1,3,3,2]

例3:

输入:[4,3,2,1]
输出:[1,2,3,4]

Notice

排列中可能包含重复的整数

遇到这种题目,只能自己找找规律:

1 5 2 3 4 / /
1 5 2 4 3 (2 1) / \ / \
1 2 3 4 5 / down swap 2 only
5 4 3 2 1 \ up ==> 极端情形(独一) (1)场景
5 2 3 1 0 \ / \ up down ==> swap(min2(down), find greater than min2), then sort left (2)场景

基本上场景就是看你数据考虑是否全面。

通过观察总结起来的做法就是:

class Solution:
    """
    @param nums: A list of integers
    @return: A list of integers
    """
    def nextPermutation(self, nums):
        # write your code here
        n = len(nums)
        i = n-1
        while i > 0 and nums[i] <= nums[i-1]:
            i -= 1
        
        if i == 0:
            return nums[::-1]
        
        assert nums[i] > nums[i-1]


        greater_index = i
        for j in range(i+1, n):
            if nums[j] > nums[i-1]:
                greater_index = j
            else:
                break
        
        assert nums[greater_index] > nums[i-1]
        
        nums[greater_index], nums[i-1] = nums[i-1], nums[greater_index]
        
        return nums[0:i] + sorted(nums[i:])

  

posted @ 2019-10-15 09:56  bonelee  阅读(146)  评论(0编辑  收藏  举报