LeetCode Permutation Sequence
Permutation Sequence for LeetCode solving
Original question
Find [1, 2, 3... N] is the largest k in the sequence composed of all numbers.
Note:
N is a number ranging from 1 to 9.
Example:
Input: n = 3, k = 3
Output: "213"
Solutions
Because n different numbers can constitute n! Then the first sequence is (n-1 )! Different possibilities, and these sequences are grouped according to the first size, 1... Is the smallest (n-1 )! , 2... Yes (n-1 )! + 1 to 2 (n-1 )! Now you only need to calculate the number of k (n-1 )! You can determine the first digit. You can also use this method to determine the second and third digits ...... In addition, since the subscript of the list starts from 0, k must be subtracted from 1.
AC Source Code
class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ k -= 1 factorial = 1 for i in range(1, n): factorial *= i result = [] array = list(range(1, n + 1)) for i in range(n - 1, 0, -1): index = k // factorial result.append(str(array[index])) array = array[:index] + array[index + 1:] k %= factorial factorial //= i result.append(str(array[0])) return "".join(result)if __name__ == "__main__": assert Solution().getPermutation(3, 3) == "213" assert Solution().getPermutation(9, 324) == "123685974"