Problem Definition:
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.
Solution:
or a permutation. Tried to use Next permutation algorithm, from the first start to Count K times, time out.
Let's analyze it ...
1._ input n, altogether there are n! species of different permutation;
2._ look at the first character: with ' 1 ' as the first character of the permutation altogether there is (n-1)! A, as a group. Similarly, the strings that start with ' 2 ', ' 3 ' 、... ' n ' are each (n-1)! A.
This forms a total of n x (n-1)!=n! permutation, which makes base= (n-1)!, which represents the number of individuals in each group currently;
3._ given a k, it will fall in a range: (m-1) x ((n-1)!) <=k<=m x ((n-1)!), where M is a number between [1, N].
4._ the M, the m-1 is the subscript I of the first character in an array of basic characters (here is NUMS=[1,2,3...N]).
5._ The above process finds the first character of the output string when input (n, K), iterates over the process until it finds a string of length n.
For each iteration, both K and base change:
K=k-i*base, where base is the individual number of each grouping in this iteration, the first base is (n-1)!, and the next time it becomes (n-2)!......
Nums.pop (i), which is the deletion of this selected character from the Nums.
Code:
1 #@param {integer} n2 #@param {integer} k3 #@return {string}4 defgetpermutation (n, k):5Permu=range (1, n+1)6res="'7 for_inchrange (n):8c,k=recur (Permu, K)9res+=Str (c)Ten returnRes One A defRecur (labels, k): -Base=reduce (LambdaX,y:x*y, Range (1, len (labels)), 1) -I=1 the whilek>i*Base: -I+=1 -I-=1 -C=Labels[i] + -k-=base*I + Labels.pop (i) A return[C, K] at
leetcode#60 permutation Sequence