LeetCode 题解工作台
排列序列
给出集合 [1,2,3,...,n] ,其所有元素共有 n! 种排列。 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" "132" "213" "231" "312" "321" 给定 n 和 k ,返回第 k 个排列。 示例 1: 输入: n = 3, k…
2
题型
7
代码语言
3
相关题
当前训练重点
困难 · 数学·递归
答案摘要
我们知道,集合 一共有 种排列,如果我们确定首位,那剩余位能组成的排列数量为 。 因此,我们枚举每一位 ,如果此时 大于当前位置确定后的排列数量,那么我们可以直接减去这个数量;否则,说明我们找到了当前位置的数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路
题目描述
给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123""132""213""231""312""321"
给定 n 和 k,返回第 k 个排列。
示例 1:
输入:n = 3, k = 3 输出:"213"
示例 2:
输入:n = 4, k = 9 输出:"2314"
示例 3:
输入:n = 3, k = 1 输出:"123"
提示:
1 <= n <= 91 <= k <= n!
解题思路
方法一:枚举
我们知道,集合 一共有 种排列,如果我们确定首位,那剩余位能组成的排列数量为 。
因此,我们枚举每一位 ,如果此时 大于当前位置确定后的排列数量,那么我们可以直接减去这个数量;否则,说明我们找到了当前位置的数。
对于每一位 ,其中 ,剩余位能组成的排列数量为 ,我们记为 。过程中已使用的数记录在 vis 中。
时间复杂度 ,空间复杂度 。
class Solution:
def getPermutation(self, n: int, k: int) -> str:
ans = []
vis = [False] * (n + 1)
for i in range(n):
fact = 1
for j in range(1, n - i):
fact *= j
for j in range(1, n + 1):
if not vis[j]:
if k > fact:
k -= fact
else:
ans.append(str(j))
vis[j] = True
break
return ''.join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of recursion and factorials.
- question_mark
Check for the ability to optimize with factorials instead of brute force generation.
- question_mark
Assess problem-solving by recursive breakdown of the sequence.
常见陷阱
外企场景- error
Misunderstanding how factorials divide the problem into smaller sections, leading to incorrect permutation generation.
- error
Failing to adjust the set of available numbers as elements are selected, causing incorrect positions.
- error
Overcomplicating the solution by generating all permutations before selecting the kth one.
进阶变体
外企场景- arrow_right_alt
Find the nth permutation in lexicographic order of a different range of numbers.
- arrow_right_alt
Use an iterative approach instead of recursion to find the kth permutation.
- arrow_right_alt
Return the kth permutation for very large values of n by optimizing factorial computations.