"Leetcode" permutation Sequence

Source: Internet
Author: User

Permutation Sequence

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.

My method determines the number of digits from high to low.

Illustrated by the legend N=3:

Build Array v={1,2,3}

Determine the highest bit:

Ind= (k-1)/2

Note: Denominator 2 refers to the number of permutations that each highest bit lasts. Since there are n-1=2 in addition to the highest bit, there are 2 of them.

The IND refers to the range of the highest position that the K-permutation is asked to fall within.

k==1,2, ind==0, the highest bit is v[ind]==1

k==3,4, Ind==1, the highest bit is v[ind]==2

k==5,6, ind==2, the highest bit is v[ind]==3

The rest of the digits are determined on a per-bit basis. Note that K's take-up update.

classSolution { Public:    stringGetpermutation (intNintk) {vector<int> V (N,0);  for(inti =0; I < n; i + +) V[i]= i+1; stringresult ="";  while(n1)        {            intdivisor = FAC (n1); intIND = (K-1)/Divisor; //itoa            stringDigit; Chartemp[ +]; sprintf (temp,"%d", V[ind]); Digit=temp; Result+=Digit;  for(inti = ind+1; I < v.size (); i + +) V[i-1] =V[i];            V.pop_back (); K%=Divisor; if(k = =0) K=Divisor; N--; }        //itoa        stringDigit; Chartemp[ +]; sprintf (temp,"%d", v[0]); Digit=temp; Result+=Digit; returnresult; }    intFacintN) {if(n = =0)            return 1; intresult =1;  for(inti =1; I <= N; i + +) Result*=i; returnresult; }};

"Leetcode" permutation Sequence

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.