# 排列序列

给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。

按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

给定 n 和 k,返回第 k 个排列。

 

示例 1:

输入:n = 3, k = 3
输出:
"213"

示例 2:

输入:n = 4, k = 9
输出:
"2314"

示例 3:

输入:n = 3, k = 1
输出:
"123"

 

提示:

以下程序实现了这一功能,请你填补空白处内容: ```python class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ import math res = [""] def generate(s, k): n = len(s) if n <= 2: if k == 2: res[0] += s[::-1] else: res[0] += s return step = math.factorial(n - 1) yu = k % step if yu == 0: yu = step c = k // step - 1 else: c = k // step res[0] += s[c] ____________________; return s = "" for i in range(1, n + 1): s += str(i) generate(s, k) return res[0] if __name__ == '__main__': s = Solution() print(s.getPermutation(3, 2)) ``` ## template ```python class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ import math res = [""] def generate(s, k): n = len(s) if n <= 2: if k == 2: res[0] += s[::-1] else: res[0] += s return step = math.factorial(n - 1) yu = k % step if yu == 0: yu = step c = k // step - 1 else: c = k // step res[0] += s[c] generate(s[:c] + s[c + 1:], yu) return s = "" for i in range(1, n + 1): s += str(i) generate(s, k) return res[0] if __name__ == '__main__': s = Solution() print(s.getPermutation(3, 2)) ``` ## 答案 ```python generate(s[:c] + s[c + 1:], yu) ``` ## 选项 ### A ```python generate(s[:c - 1] + s[c + 1:], yu) ``` ### B ```python generate(s[:c + 1] + s[c - 1:], yu) ``` ### C ```python generate(s[:c] + s[c:], yu) ```