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.
Idea: Look at an example of n=4:k=15. The size of each color block is (n-1)! = 6. K is in the third color block, so the 1th number is 3. The recursive function is then called in the purple block, which is our remaining number is [124], the equivalent of k = 15-6*2 = 3. The boundary condition is len (nums) = = 1. Note that the operation in the first color block is (k-1)//factorial (n-1), and the first k element in the matrix is in which row is similar.
1 classsolution (object):2 defgetpermutation (self, n, k):3 """4 : Type N:int5 : Type K:int6 : Rtype:str7 """8Nums = List (range (1, n+1))9res = []Ten self.helper (Nums, res, k) OneA =map (str, RES) A return "'. Join (a) - - defHelper (self, nums, res, k): the -n =Len (nums) - ifn = = 1: -Res + =Nums + return - +i = (k-1)/math.factorial (n-1) ARes + =[Nums[i]] atNums = nums[:i]+nums[i+1:] -K = K-i*math.factorial (n-1) - self.helper (Nums, res, k) -
Leetcode 60. Permutation Sequence