Source of the topic
https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must is in-place, do not allocate extra memory.
Test instructions Analysis
Input: An array
Output: An array (in-situ operation)
Conditions: The output array is the next larger array than the input array. such as [1, 2, 3] = = [1, 3, 2]
If the input is the largest, then the output is the smallest array. such as [3, 2, 1] = = [1, 2, 3]
Topic ideas
- From the back forward to find the first larger than the previous number, if not, it is already the largest array, directly in the ascending sort (List.sort ()) return
- If you find the maximum value, record its position index, and then find a minimum value that is larger than nums[index-1] after index (including index) and swap it with nums[index-1]
- Bubbles sort the nums array elements after index (including index)
AC Code (PYTHON)
1_author_ ="YE"2 #-*-coding:utf-8-*-3 classsolution (object):4 defnextpermutation (Self, nums):5 """6 : Type Nums:list[int]7 : Rtype:void does not return anything, modify Nums in-place instead.8 """9 #print (nums)TenLen1 =Len (nums) Oneindex =-1 A forIinchRange (len1-1): - ifNums[len1-1-i] > nums[len1-i-2]: -index = len1-1-I the Break - ifindex = =-1: - Nums.sort () - Else: +Minindex =Index -MinValue =Nums[index] + forIinchRange (len1-index-1): A ifMinValue > Nums[index + i + 1] > Nums[index-1]: atMinindex = index + i + 1 -MinValue =Nums[minindex] - -Nums[minindex] = nums[index-1] -NUMS[INDEX-1] =MinValue - in #sort other numbers from index -Numbers = Len1-Index to #print (Numbers) + forIinchRange (numbers-1): - Print('I:', i) the forJinchRange (Numbers-i-1): * ifNUMS[LEN1-J-1] < nums[len1-j-2]: $temp = nums[len1-j-1]Panax NotoginsengNums[len1-j-1] = nums[len1-j-2] -Nums[len1-j-2] =Temp the + #print (Minindex, minvalue) A #print (nums)
View Code
[Leetcode] (python): 031-next permutation