[Leetcode] (python): 031-next permutation

Source: Internet
Author: User

Source of the topic:

https://leetcode.com/problems/next-permutation/

Test Instructions Analysis:

Enter an array. Output the next larger array of these number combinations than the input. If the input is the largest, then the output is the smallest array. For example, the 1,3,2 output. and 3,2,1 output.

Topic Ideas:

If there is a larger array than the input array nums, then there is bound to be nums[i] < Nums[j] (I < j). The smallest array larger than the Nums, then the first nums[i] < Nums[i + 1] When the last number is compared, the last number of nums[i] and I + 1 later than Nums[i], and then the "I" after the number of orders, then get the answer.

Code (Python):

  

1 classSolution (Object):2 def nextpermutation (self, nums):3         """4: Type nums:list[int]5: Rtype:voidDo notreturnAnything, modify Numsinch-Place instead.6         """7Size =Len (nums)8         ifSize = =0or size = =1:9             returnTeni = size-2 One          whileI >=0: A             ifNums[i] < Nums[i +1]: -j = i +1 -                  whileJ <Size: the                     ifNums[i] >=Nums[j]: -                          Break -J + =1 -J-=1 +NUMS[I],NUMS[J] =Nums[j],nums[i] -Nums[i +1:] = sorted (nums[i +1:]) +                 return AI-=1 atMiddle = (Size-1)//2;k = 0 -          whileK <=Middle: -Nums[k],nums[size-1-K] = nums[size-1-K],nums[k] -K + =1 -         return
View Code

Reprint Please specify source: http://www.cnblogs.com/chruny/p/4918297.html

[Leetcode] (python): 031-next permutation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.