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):
"123"
"132"
"213"
"231"
"312"
"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