60. 排列序列

2022/06/03 leetcode 共 666 字,约 2 分钟

title

problem link

给出集合 [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"

提示:

  • 1 <= n <= 9
  • 1 <= k <= n!

solution

一层一层递进。k-=1,转换成0开始更容易。

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        import sortedcontainers
        res = sortedcontainers.SortedList(list(range(1, n + 1)))
        ans = ""
        k -= 1  # 转换成0开始
        import math
        def calcu(x):
            r = 1
            for i in range(2, x + 1):
                r *= i
            return r

        def dfs(used: list):
            nonlocal k
            # print(used, k)
            if len(res) == 1:
                nonlocal ans
                ans = used + [res[0]]
                ans = map(str, ans)
                ans = "".join(ans)
                return
            left = len(res) - 1
            j = calcu(left)
            x = k // j
            k %= j
            used.append(res[x])
            del res[x]
            dfs(used)

        dfs([])
        return ans

Search

    Table of Contents