[Leetcode] Permutation sequnce

Source: Internet
Author: User

Original title address: https://oj.leetcode.com/submissions/detail/5341904/

Test instructions

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

Given n and K, return the kth permutation sequence.

Note: Given N would be between 1 and 9 inclusive.

Problem-solving ideas: Just started with DFS, but has been tle. It seems that Python is really slow to write Dfs in Java and C + +. Can only adopt a more ingenious way of thinking.

     

In fact, the data is not big, n up to 9,9! = 362880, the enumeration should be able to pass (I did not experiment).

The method I used was to calculate the K-permutation.

Suppose n = 6,k = 400

The first digit is calculated first,

The first bit is 6, so it's also the 5th at least! * 5 + 1 permutations, this is because when the first bit is 1/2/3/4/5, there are 5! permutations, so the first bit is 6 o'clock, at least the 5th! * 5 + 1 permutations (this arrangement is 612345).

5! * 5 + 1 = 601 > K, so the first bit cannot be 6.

Enumerate one by one until the first bit is 4 o'clock, at which point 4xxxxx is at least 5th! * 3 + 1 = 361 permutations.

Then the second digit is calculated,

The difference with the first digit is that the 46xxxx is at least 4th! * 4 + 1 = 97 permutations, this is because the smaller than 6 is only 5/3/2/1.

Finally, we can calculate the second bit as 2.

Finally, the No. 400 arrangement was 425361.

Code:

classSolution:#@return A string    defgetpermutation (self, n, k):#http://www.cnblogs.com/zuoyuan/p/3785530.htmlres ="'FAC= 1k-= 1 forIinchRange (1,n): FAC *=I num= [I forIinchRange (1,10)]         forIinchReversed (range (n)): Curr= num[k/FAC] Res+=Str (curr) num.remove (curr)ifI! =0:k%=FAC FAC/=IreturnRes

Reference:

Http://www.cnblogs.com/zuoyuan/p/3785530.html

[Leetcode] Permutation sequnce

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.