Skip to content

Commit d541a37

Browse files
author
lucifer
committed
feat: 回溯,$140 $ 816
1 parent 3a21840 commit d541a37

File tree

6 files changed

+370
-2
lines changed

6 files changed

+370
-2
lines changed

SUMMARY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@
168168
* [0718. 最长重复子数组](problems/718.maximum-length-of-repeated-subarray.md)
169169
* [0754. 到达终点数字](problems/754.reach-a-number.md)
170170
* [0785. 判断二分图](problems/785.is-graph-bipartite.md)
171+
* [0816.ambiguous-coordinates](problems/816.ambiguous-coordinates.md)
171172
* [0820. 单词的压缩编码](problems/820.short-encoding-of-words.md)
172173
* [0875. 爱吃香蕉的珂珂](problems/875.koko-eating-bananas.md)
173174
* [0877. 石子游戏](problems/877.stone-game.md)
@@ -209,6 +210,7 @@
209210
* [0085. 最大矩形](problems/85.maximal-rectangle.md)
210211
* [0124. 二叉树中的最大路径和](problems/124.binary-tree-maximum-path-sum.md)
211212
* [0128. 最长连续序列](problems/128.longest-consecutive-sequence.md)
213+
* [0140. 单词拆分 II](problems/140.word-break-ii.md)
212214
* [0145. 二叉树的后序遍历](problems/145.binary-tree-postorder-traversal.md)
213215
* [0212. 单词搜索 II](problems/212.word-search-ii.md)
214216
* [0239. 滑动窗口最大值](problems/239.sliding-window-maximum.md)

collections/hard.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
- [0085. 最大矩形](../problems/85.maximal-rectangle.md)
3636
- [0124. 二叉树中的最大路径和](../problems/124.binary-tree-maximum-path-sum.md)
3737
- [0128. 最长连续序列](../problems/128.longest-consecutive-sequence.md)
38+
- [0140. 单词拆分 II](problems/140.word-break-ii.md) 🆕
3839
- [0145. 二叉树的后序遍历](../problems/145.binary-tree-postorder-traversal.md)
3940
- [0212. 单词搜索 II](../problems/212.word-search-ii.md)
4041
- [0239. 滑动窗口最大值](../problems/239.sliding-window-maximum.md)

collections/medium.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@
9191
- [0718. 最长重复子数组](../problems/718.maximum-length-of-repeated-subarray.md)
9292
- [0754. 到达终点数字](../problems/754.reach-a-number.md)
9393
- [0785. 判断二分图](../problems/785.is-graph-bipartite.md)
94+
- [0816.ambiguous-coordinates](../problems/816.ambiguous-coordinates.md) 🆕
9495
- [0820. 单词的压缩编码](../problems/820.short-encoding-of-words.md)
9596
- [0875. 爱吃香蕉的珂珂](../problems/875.koko-eating-bananas.md)
9697
- [0877. 石子游戏](../problems/877.stone-game.md)

problems/140.word-break-ii.md

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
## 题目地址(140. 单词拆分 II)
2+
3+
https://leetcode-cn.com/problems/word-break-ii/
4+
5+
## 题目描述
6+
7+
```
8+
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
9+
10+
说明:
11+
12+
分隔时可以重复使用字典中的单词。
13+
你可以假设字典中没有重复的单词。
14+
示例 1:
15+
16+
输入:
17+
s = "catsanddog"
18+
wordDict = ["cat", "cats", "and", "sand", "dog"]
19+
输出:
20+
[
21+
  "cats and dog",
22+
  "cat sand dog"
23+
]
24+
示例 2:
25+
26+
输入:
27+
s = "pineapplepenapple"
28+
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
29+
输出:
30+
[
31+
  "pine apple pen apple",
32+
  "pineapple pen apple",
33+
  "pine applepen apple"
34+
]
35+
解释: 注意你可以重复使用字典中的单词。
36+
示例 3:
37+
38+
输入:
39+
s = "catsandog"
40+
wordDict = ["cats", "dog", "sand", "and", "cat"]
41+
输出:
42+
[]
43+
44+
```
45+
46+
微软有一道题和这个一样 [题目地址](https://github.com/azl397985856/fe-interview/issues/153) 一样,感兴趣的可以看看完整面经。
47+
48+
## 前置知识
49+
50+
- 回溯
51+
- 笛卡尔积
52+
53+
## 公司
54+
55+
- 暂无
56+
57+
## 暴力回溯
58+
59+
### 思路
60+
61+
实际上这道题就是暴力回溯就好了, 代码也比较简单。
62+
63+
### 代码
64+
65+
代码支持:Python3
66+
67+
Python3 Code:
68+
69+
```py
70+
class Solution:
71+
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
72+
ans = []
73+
n = len(s)
74+
75+
def backtrack(temp, start):
76+
if start == n: ans.append(temp[1:])
77+
for i in range(start, n):
78+
if s[start:i + 1] in wordDict:
79+
backtrack(temp + " " + s[start:i + 1], i + 1)
80+
backtrack('', 0)
81+
return ans
82+
```
83+
84+
**复杂度分析**
85+
86+
- 时间复杂度:$O(2^N)$
87+
- 空间复杂度:$O(2^N)$
88+
89+
## 笛卡尔积优化
90+
91+
### 思路
92+
93+
上面的代码会超时,测试用例会挂在如下:
94+
95+
```js
96+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"[
97+
("a",
98+
"aa",
99+
"aaa",
100+
"aaaa",
101+
"aaaaa",
102+
"aaaaaa",
103+
"aaaaaaa",
104+
"aaaaaaaa",
105+
"aaaaaaaaa",
106+
"aaaaaaaaaa")
107+
];
108+
```
109+
110+
也就是说 s 的长度是 151, 这超时也就能够理解了,但是力扣的题目描述没有给数据范围。 **如果是真实的面试, 一定先问清楚数据范围**
111+
112+
接下来,我们考虑优化。
113+
114+
通过观察发现, 对于一个字符串 s,比如 "helloworldhi" 而言,假设 dict 为:
115+
116+
```js
117+
{
118+
hi: true,
119+
h: true,
120+
i: true,
121+
world: true,
122+
hello: true,
123+
124+
}
125+
```
126+
127+
1. 当我们 DFS 探到底部的时候,也就是触及到 hi。我们就知道了,s[-2:] 可能组成的所有可能就是 ['hi', 'h', 'i']
128+
2. 当我们 DFS 探到 worldhi 的时候。我们就知道了,s[-7:] 可能组成的所有可能就是 ['worldhi', 'worldh', 'worldi']
129+
3. 如上只是一个分支的情况,如果有多个分支,那么步骤 1 就会被重复计算。
130+
131+
我们也不难看出, 当我们 DFS 探到 worldhi 的时候,其可能的结果就是探测到的单词和上一步的所有可能的笛卡尔积。
132+
133+
因此一种优化思路就是将回溯的结果通过返回值的形式传递给父级函数,父级函数通过笛卡尔积构造 ans 即可。而这实际上和上面的解法复杂度是一样的, 但是经过这样的改造,我们就可以使用记忆化技巧减少重复计算了。因此理论上, 我们不存在**回溯**过程了。 因此时间复杂度就是所有的组合,即一次遍历以及内部的笛卡尔积,也就是 $O(N ^ 2)$。
134+
135+
### 代码
136+
137+
代码支持:Python3
138+
139+
Python3 Code:
140+
141+
```py
142+
class Solution:
143+
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
144+
n = len(s)
145+
@lru_cache(None)
146+
def backtrack(start):
147+
ans = []
148+
if start == n:
149+
ans.append('')
150+
for i in range(start, n):
151+
if s[start:i + 1] in wordDict:
152+
if start == 0: temp = s[start:i + 1]
153+
else: temp = " " + s[start:i + 1]
154+
ps = backtrack(i + 1)
155+
for p in ps:
156+
ans.append(temp + p)
157+
return ans
158+
return backtrack(0)
159+
```
160+
161+
**复杂度分析**
162+
163+
- 时间复杂度:$O(N^2)$
164+
- 空间复杂度:$O(N^2)$
165+
166+
这种记忆化递归的方式和 DP 思想一模一样, 大家可以将其改造为 DP,这个留给大家来完成。
167+
168+
更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。
169+
170+
关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。
171+
172+
![](https://tva1.sinaimg.cn/large/007S8ZIlly1gfcuzagjalj30p00dwabs.jpg)

problems/816.ambiguous-coordinates.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
## 题目地址(816. 模糊坐标)
2+
3+
https://leetcode-cn.com/problems/ambiguous-coordinates
4+
5+
## 题目描述
6+
7+
```
8+
我们有一些二维坐标,如 "(1, 3)" 或 "(2, 0.5)",然后我们移除所有逗号,小数点和空格,得到一个字符串S。返回所有可能的原始字符串到一个列表中。
9+
10+
原始的坐标表示法不会存在多余的零,所以不会出现类似于"00", "0.0", "0.00", "1.0", "001", "00.01"或一些其他更小的数来表示坐标。此外,一个小数点前至少存在一个数,所以也不会出现“.1”形式的数字。
11+
12+
最后返回的列表可以是任意顺序的。而且注意返回的两个数字中间(逗号之后)都有一个空格。
13+
14+
 
15+
16+
示例 1:
17+
输入: "(123)"
18+
输出: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
19+
示例 2:
20+
输入: "(00011)"
21+
输出:  ["(0.001, 1)", "(0, 0.011)"]
22+
解释:
23+
0.0, 00, 0001 或 00.01 是不被允许的。
24+
示例 3:
25+
输入: "(0123)"
26+
输出: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]
27+
示例 4:
28+
输入: "(100)"
29+
输出: [(10, 0)]
30+
解释:
31+
1.0 是不被允许的。
32+
 
33+
34+
提示:
35+
36+
4 <= S.length <= 12.
37+
S[0] = "(", S[S.length - 1] = ")", 且字符串 S 中的其他元素都是数字。
38+
39+
```
40+
41+
## 前置知识
42+
43+
- 回溯
44+
- 笛卡尔积
45+
46+
## 公司
47+
48+
- 暂无
49+
50+
## 思路
51+
52+
这个也是一个明显的笛卡尔积的题目。
53+
54+
我们先将题目简化一下,不考虑题目给的那些限制, 只要将其分割成逗号分割的两部分即可,不用考虑是否是有效的(比如不能是 001 等)。
55+
56+
那么代码大概是:
57+
58+
Python3 Code:
59+
60+
```python
61+
class Solution:
62+
63+
def subset(self, s: str):
64+
ans = []
65+
for i in range(1, len(s)):
66+
ans.append(s[:i] + "." + s[i:])
67+
ans.append(s)
68+
return ans
69+
70+
def ambiguousCoordinates(self, s: str) -> List[str]:
71+
ans = []
72+
s = s[1:-1]
73+
for i in range(1, len(s)):
74+
x = self.subset(s[:i])
75+
y = self.subset(s[i:])
76+
for i in x:
77+
for j in y:
78+
ans.append('(' + i + ', ' + j + ')')
79+
return ans
80+
81+
```
82+
83+
我简单解释一下上面代码的意思。
84+
85+
- 将字符串分割成两部分, 其所有的可能性无非就是枚举切割点,这里使用了一个 for 循环。
86+
- subset(s) 的功能是在 s 的第 0 位后,第一位后,第 n - 2 位后插入一个小数点 ".",其实就是构造一个有效的数字而已。
87+
- 因此 x 和 y 就是分割形成的两部分的有效分割集合,**答案自然就是 x 和 y 的笛卡尔积**
88+
89+
如果上面的代码你会了,这道题无非就是增加几个约束, 我们剪几个不合法的枝即可。具体代码见下方代码区,可以看出,代码仅仅是多了几个 if 判断而已。
90+
91+
上面的目标很常见,请**务必掌握**
92+
93+
## 关键点
94+
95+
- 笛卡尔积优化
96+
97+
## 代码
98+
99+
代码支持:Python3
100+
101+
```python
102+
class Solution:
103+
# "123" => ["1.23", "12.3", "123"]
104+
def subset(self, s: str):
105+
ans = []
106+
107+
# 带小数点的
108+
for i in range(1, len(s)):
109+
# 不允许 00.111, 0.0,01.1,1.0
110+
if s[0] == '0' and i > 1:
111+
continue
112+
if s[-1] == '0':
113+
continue
114+
ans.append(s[:i] + "." + s[i:])
115+
# 不带小数点的(不允许 001)
116+
if s == '0' or not s.startswith('0'):
117+
ans.append(s)
118+
return ans
119+
120+
def ambiguousCoordinates(self, s: str) -> List[str]:
121+
ans = []
122+
s = s[1:-1]
123+
for i in range(1, len(s)):
124+
x = self.subset(s[:i])
125+
y = self.subset(s[i:])
126+
for i in x:
127+
for j in y:
128+
ans.append('(' + i + ', ' + j + ')')
129+
return ans
130+
131+
```
132+
133+
**复杂度分析**
134+
135+
- 时间复杂度:$O(N^3)$
136+
- 空间复杂度:$O(N^2)$
137+
138+
更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。
139+
140+
关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。
141+
142+
![](https://tva1.sinaimg.cn/large/007S8ZIlly1gfcuzagjalj30p00dwabs.jpg)

0 commit comments

Comments
 (0)