Permutation Sequence Java Solutions

Source: Internet
Author: User

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.

1  Public classSolution {2      PublicString Getpermutation (intNintk) {3StringBuilder ans =NewStringBuilder ();4StringBuilder tmp =NewStringBuilder ();5          for(inti = 1; i<=n; i++) tmp.append (i);6         intFactor =calculate (n);7         intindex = 0;8          for(inti = n; i>=1; i--){9Factor/=i;Tenindex = (k-1)/factor; One ans.append (Tmp.charat (index)); AK-= index*factor; - Tmp.deletecharat (index); -         } the         returnans.tostring (); -     } -      -      Public intCalculateintN) { +         intsum = 1; -          for(;n>=1; n--){ +Sum *=N; A         } at         returnsum; -     } -}

N Number of permutation total has n factorial, based on this property we can get a corresponding number of which is. The idea is that, for example, the current length is n, and we know that each of the same starting elements corresponds (N-1)! A permutation,

That is (n-1)! After a permutation, a starting element is changed. Therefore, as long as the current k is carried out (N-1)! The resulting number is the index of the current remaining array so that the corresponding element can be obtained.

Https://discuss.leetcode.com/topic/17348/explain-like-i-m-five-java-solution-in-o-n

Permutation Sequence Java Solutions

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.