• 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:])
    

      

  • 相关阅读:
    Mac pycharm专业版安装以及破解方法
    Django 错误之 No module named ‘MySQLdb’
    archery部署
    MySQL监控内容
    mac安装神器brew
    4. 寻找两个有序数组的中位数
    7.整数反转
    2.两数相加
    1. 两数之和
    141. 环形链表
  • 原文地址:https://www.cnblogs.com/bonelee/p/11675807.html
Copyright © 2020-2023  润新知