1. 程式人生 > >python leetcode 31. Next Permutation

python leetcode 31. Next Permutation

思路從尾部遍歷找到相對較大值,再從尾部遍歷找到恰好比它後一個值小的數字,這兩個數字互換再翻轉 比如 156432 第一次迴圈先定位到6,第二次迴圈定位到6,6和5互換,165432,後面的數字再翻轉,162345

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
l1 = len(nums) if l1 > 1: flag = 0 for i in range(l1-1,0,-1): if nums[i] > nums[i-1]: flag = 1 break if flag == 0: nums[:]=nums[:][::-1] else: for
j in range(l1-1,i-1,-1): if nums[j] > nums[i-1]: nums[i-1],nums[j] = nums[j],nums[i-1] nums[i:]=nums[i:][::-1] break