Skip to content

Commit cdc6a17

Browse files
author
lucifer
committed
feat: #60
1 parent 709e61a commit cdc6a17

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ leetcode 题解,记录自己的 leetcode 解题之路。
165165
- [0049.group-anagrams](./problems/49.group-anagrams.md)
166166
- [0055.jump-game](./problems/55.jump-game.md)
167167
- [0056.merge-intervals](./problems/56.merge-intervals.md)
168+
- [0060.permutation-sequence](./problems/60.permutation-sequence.md) 🆕
168169
- [0062.unique-paths](./problems/62.unique-paths.md)
169170
- [0073.set-matrix-zeroes](./problems/73.set-matrix-zeroes.md)
170171
- [0075.sort-colors](./problems/75.sort-colors.md)

problems/60.permutation-sequence.md

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
## 题目地址(第 K 个排列)
2+
3+
https://leetcode-cn.com/problems/permutation-sequence/description/
4+
5+
## 标签
6+
7+
- 数学
8+
- 回溯
9+
- 找规律
10+
- factorial
11+
12+
## 公司
13+
14+
Twitter
15+
16+
## 题目描述
17+
18+
```
19+
给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
20+
21+
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
22+
23+
"123"
24+
"132"
25+
"213"
26+
"231"
27+
"312"
28+
"321"
29+
给定 n 和 k,返回第 k 个排列。
30+
31+
说明:
32+
33+
给定 n 的范围是 [1, 9]。
34+
给定 k 的范围是[1, n!]。
35+
示例 1:
36+
37+
输入: n = 3, k = 3
38+
输出: "213"
39+
示例 2:
40+
41+
输入: n = 4, k = 9
42+
输出: "2314"
43+
```
44+
45+
## 思路
46+
47+
LeetCode 上关于排列的题目截止目前(2020-01-06)主要有三种类型:
48+
49+
- 生成全排列
50+
- 生成下一个排列
51+
- 生成第 k 个排列(我们的题目就是这种)
52+
53+
我们不可能求出所有的排列,然后找到第 k 个之后返回。因为排列的组合是 N!,要比 2^n 还要高很多,非常有可能超时。我们必须使用一些巧妙的方法。
54+
55+
我们以题目中的 n= 3 k = 3 为例:
56+
57+
- "123"
58+
- "132"
59+
- "213"
60+
- "231"
61+
- "312"
62+
- "321"
63+
64+
可以看出 1xx,2xx 和 3xx 都有两个,如果你知道阶乘的话,实际上是 2!个。 我们想要找的是第 3 个。那么我们可以直接跳到 2 开头,我们排除了以 1 开头的排列,问题缩小了,我们将 2 加入到结果集,我们不断重复上述的逻辑,知道结果集的元素为 n 即可。
65+
66+
## 关键点解析
67+
68+
- 找规律
69+
- 排列组合
70+
71+
## 代码
72+
73+
- 语言支持: Python3
74+
75+
```python
76+
import math
77+
78+
class Solution:
79+
def getPermutation(self, n: int, k: int) -> str:
80+
res = ""
81+
candidates = [str(i) for i in range(1, n + 1)]
82+
83+
while n != 0:
84+
facto = math.factorial(n - 1)
85+
# i 表示前面被我们排除的组数,也就是k所在的组的下标
86+
# k // facto 是不行的, 加入k % facto == 0就会有问题
87+
i = math.ceil(k / facto) - 1
88+
# 我们把candidates[i]加入到结果集,然后将其弹出candidates(不能重复使用元素)
89+
res += candidates[i]
90+
candidates.pop(i)
91+
# k 缩小了 facto* i
92+
k -= facto * i
93+
# 每次迭代我们实际上就处理了一个元素,n 减去 1,当n == 0 说明全部处理完成,我们退出循环
94+
n -= 1
95+
return res
96+
```

0 commit comments

Comments
 (0)