Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0199e7f

Browse files
✨feat: Add 488
1 parent 9279b32 commit 0199e7f

File tree

3 files changed

+270
-0
lines changed

3 files changed

+270
-0
lines changed

‎Index/DFS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
| [341. 扁平化嵌套列表迭代器](https://leetcode-cn.com/problems/flatten-nested-list-iterator/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/flatten-nested-list-iterator/solution/yi-ti-shuang-jie-dfsdui-lie-di-gui-zhan-kvwhy/) | 中等 | 🤩🤩🤩 |
1212
| [403. 青蛙过河](https://leetcode-cn.com/problems/frog-jump/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/frog-jump/solution/gong-shui-san-xie-yi-ti-duo-jie-jiang-di-74fw/) | 困难 | 🤩🤩🤩🤩 |
1313
| [437. 路径总和 III](https://leetcode-cn.com/problems/path-sum-iii/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/path-sum-iii/solution/gong-shui-san-xie-yi-ti-shuang-jie-dfs-q-usa7/) | 中等 | 🤩🤩🤩🤩 |
14+
| [488. 祖玛游戏](https://leetcode-cn.com/problems/zuma-game/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/zuma-game/solution/gong-shui-san-xie-yi-ti-shuang-jie-sou-s-3ftb/) | 困难 | 🤩🤩🤩🤩 |
1415
| [494. 目标和](https://leetcode-cn.com/problems/target-sum/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/target-sum/solution/gong-shui-san-xie-yi-ti-si-jie-dfs-ji-yi-et5b/) | 中等 | 🤩🤩🤩🤩 |
1516
| [638. 大礼包](https://leetcode-cn.com/problems/shopping-offers/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/shopping-offers/solution/gong-shui-san-xie-yi-ti-shuang-jie-zhuan-qgk1/) | 中等 | 🤩🤩🤩🤩 |
1617
| [690. 员工的重要性](https://leetcode-cn.com/problems/employee-importance/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/employee-importance/solution/gong-shui-san-xie-yi-ti-shuang-jie-di-gu-s79x/) | 简单 | 🤩🤩🤩 |

‎Index/启发式搜索.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
| 题目 | 题解 | 难度 | 推荐指数 |
22
| ------------------------------------------------------------ | ------------------------------------------------------------ | ---- | -------- |
33
| [127. 单词接龙](https://leetcode-cn.com/problems/word-ladder/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/word-ladder/solution/gong-shui-san-xie-ru-he-shi-yong-shuang-magjd/) | 困难 | 🤩🤩🤩🤩🤩 |
4+
| [488. 祖玛游戏](https://leetcode-cn.com/problems/zuma-game/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/zuma-game/solution/gong-shui-san-xie-yi-ti-shuang-jie-sou-s-3ftb/) | 困难 | 🤩🤩🤩🤩 |
45
| [752. 打开转盘锁](https://leetcode-cn.com/problems/open-the-lock/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/open-the-lock/solution/gong-shui-san-xie-yi-ti-shuang-jie-shuan-wyr9/) | 中等 | 🤩🤩🤩🤩 |
56
| [773. 滑动谜题](https://leetcode-cn.com/problems/sliding-puzzle/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/sliding-puzzle/solution/gong-shui-san-xie-fa-hui-a-suan-fa-zui-d-3go8/) | 困难 | 🤩🤩🤩🤩 |
67
| [847. 访问所有节点的最短路径](https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes/) | [LeetCode 题解链接](https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes/solution/gong-shui-san-xie-yi-ti-shuang-jie-bfs-z-6p2k/) | 困难 | 🤩🤩🤩🤩🤩 |
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
### 题目描述
2+
3+
这是 LeetCode 上的 **[488. 祖玛游戏](https://leetcode-cn.com/problems/zuma-game/solution/gong-shui-san-xie-yi-ti-shuang-jie-sou-s-3ftb/)** ,难度为 **困难**
4+
5+
Tag : 「DFS」、「搜索」、「启发式搜索」
6+
7+
8+
9+
你正在参与祖玛游戏的一个变种。
10+
11+
在这个祖玛游戏变体中,桌面上有 一排 彩球,每个球的颜色可能是:红色 `'R'`、黄色 `'Y'`、蓝色 `'B'`、绿色 `'G'` 或白色 `'W'` 。你的手中也有一些彩球。
12+
13+
你的目标是 清空 桌面上所有的球。每一回合:
14+
15+
* 从你手上的彩球中选出 任意一颗 ,然后将其插入桌面上那一排球中:两球之间或这一排球的任一端。
16+
* 接着,如果有出现 三个或者三个以上 且 颜色相同 的球相连的话,就把它们移除掉。
17+
* 如果这种移除操作同样导致出现三个或者三个以上且颜色相同的球相连,则可以继续移除这些球,直到不再满足移除条件。
18+
* 如果桌面上所有球都被移除,则认为你赢得本场游戏。
19+
* 重复这个过程,直到你赢了游戏或者手中没有更多的球。
20+
21+
给你一个字符串 board ,表示桌面上最开始的那排球。另给你一个字符串 hand ,表示手里的彩球。请你按上述操作步骤移除掉桌上所有球,计算并返回所需的 最少 球数。如果不能移除桌上所有的球,返回 -1 。
22+
23+
示例 1:
24+
```
25+
输入:board = "WRRBBW", hand = "RB"
26+
27+
输出:-1
28+
29+
解释:无法移除桌面上的所有球。可以得到的最好局面是:
30+
- 插入一个 'R' ,使桌面变为 WRRRBBW 。WRRRBBW -> WBBW
31+
- 插入一个 'B' ,使桌面变为 WBBBW 。WBBBW -> WW
32+
桌面上还剩着球,没有其他球可以插入。
33+
```
34+
示例 2:
35+
```
36+
输入:board = "WWRRBBWW", hand = "WRBRW"
37+
38+
输出:2
39+
40+
解释:要想清空桌面上的球,可以按下述步骤:
41+
- 插入一个 'R' ,使桌面变为 WWRRRBBWW 。WWRRRBBWW -> WWBBWW
42+
- 插入一个 'B' ,使桌面变为 WWBBBWW 。WWBBBWW -> WWWW -> empty
43+
只需从手中出 2 个球就可以清空桌面。
44+
```
45+
示例 3:
46+
```
47+
输入:board = "G", hand = "GGGGG"
48+
49+
输出:2
50+
51+
解释:要想清空桌面上的球,可以按下述步骤:
52+
- 插入一个 'G' ,使桌面变为 GG 。
53+
- 插入一个 'G' ,使桌面变为 GGG 。GGG -> empty
54+
只需从手中出 2 个球就可以清空桌面。
55+
```
56+
示例 4:
57+
```
58+
输入:board = "RBYYBBRRB", hand = "YRBGB"
59+
60+
输出:3
61+
62+
解释:要想清空桌面上的球,可以按下述步骤:
63+
- 插入一个 'Y' ,使桌面变为 RBYYYBBRRB 。RBYYYBBRRB -> RBBBRRB -> RRRB -> B
64+
- 插入一个 'B' ,使桌面变为 BB 。
65+
- 插入一个 'B' ,使桌面变为 BBB 。BBB -> empty
66+
只需从手中出 3 个球就可以清空桌面。
67+
```
68+
69+
提示:
70+
* 1 <= board.length <= 16
71+
* 1 <= hand.length <= 5
72+
* board 和 hand 由字符 `'R'``'Y'``'B'``'G'``'W'` 组成
73+
* 桌面上一开始的球中,不会有三个及三个以上颜色相同且连着的球
74+
75+
---
76+
77+
### 搜索 + 剪枝
78+
79+
数据范围 1ドル <= board.length <= 16$ 和 1ドル <= hand.length <= 5$。
80+
81+
为了方便,我们使用 $a$ 和 $b$ 来代指 $board$ 和 $hand$。
82+
83+
但在爆搜过程中同时维持两个字符串构造会超时,考虑使用一个 `int` 来记录 $hand$ 的使用情况。
84+
85+
![image.png](https://pic.leetcode-cn.com/1636422194-vvIBfl-image.png)
86+
87+
代码:
88+
```Java
89+
class Solution {
90+
int INF = 0x3f3f3f3f;
91+
String b;
92+
int m;
93+
Map<String, Integer> map = new HashMap<>();
94+
public int findMinStep(String a, String _b) {
95+
b = _b;
96+
m = b.length();
97+
int ans = dfs(a, 1 << m);
98+
return ans == INF ? -1 : ans;
99+
}
100+
int dfs(String a, int cur) {
101+
if (a.length() == 0) return 0;
102+
if (map.containsKey(a)) return map.get(a);
103+
int ans = INF;
104+
int n = a.length();
105+
for (int i = 0; i < m; i++) {
106+
if (((cur >> i) & 1) == 1) continue;
107+
int next = (1 << i) | cur;
108+
for (int j = 0; j <= n; j++) {
109+
StringBuilder sb = new StringBuilder();
110+
sb.append(a.substring(0, j)).append(b.substring(i, i + 1));
111+
if (j != n) sb.append(a.substring(j));
112+
int k = j;
113+
while (0 <= k && k < sb.length()) {
114+
char c = sb.charAt(k);
115+
int l = k, r = k;
116+
while (l >= 0 && sb.charAt(l) == c) l--;
117+
while (r < sb.length() && sb.charAt(r) == c) r++;
118+
if (r - l - 1 >= 3) {
119+
sb.delete(l + 1, r);
120+
k = l >= 0 ? l : r;
121+
} else {
122+
break;
123+
}
124+
}
125+
ans = Math.min(ans, dfs(sb.toString(), next) + 1);
126+
}
127+
}
128+
map.put(a, ans);
129+
return ans;
130+
}
131+
}
132+
```
133+
* 时间复杂度:略。「爆搜」同时还得考虑「剪枝」的复杂度分析意义不大。
134+
* 空间复杂度:略
135+
136+
---
137+
138+
### AStar 算法
139+
140+
我们建立一个类 `Node` 来代指当前搜索局面。
141+
142+
```Java
143+
class Node {
144+
// 当前的棋盘状况
145+
String a;
146+
// cur 代表当前 hand 的使用情况(若 cur 二进制表示中的第 k 位为 1,代表 hand 的第 k 个彩球已被使用)
147+
// val 代表「当前棋盘为 a」和「hand 使用情况为 cur」的情况下,至少还需要多少步才能将 a 全部消掉(启发式估算值)
148+
// step 代表当前局面是经过多少步而来
149+
int cur, val, step;
150+
Node (String _a, int _c, int _v, int _s) {
151+
a = _a;
152+
cur = _c; val = _v; step = _s;
153+
}
154+
}
155+
```
156+
157+
显然,直接对此进行 `BFS`,会 TLE。
158+
159+
我们考虑将优化 `BFS` 中使用到的队列改为优先队列:**更接近答案的局面先出队进行局面延展。**
160+
161+
然后我们考虑如何设计 AStar 的启发式函数。
162+
163+
**首先,一个合格的 AStar 启发式函数应当能够确保「估值不会小于理论最小距离」。同时由于启发式的估值函数是针对于最终状态进行估算,因此只确保最终状态的第一次出队时为最短路,其余中间状态的首次出队不一定是最短路,为此我们需要使用哈希表来记录中间状态的距离变化,如果某个局面的最短距离被更新,我们应当将其再次入队。**
164+
165+
基于此,我们设计如下的 AStar 的启发式函数:使用哈希表来统计「当前的棋盘 $a$ 的彩球数量」&「当前手上拥有的彩球数量」,对「无解情况」和「理论最小次数」进行分析:
166+
167+
* 对于某个彩球 $c$ 而言,如果当前棋盘的数量 + 手上的数量 都不足 3ドル$ 个,那么该局面往下搜索也必然无解,该局面无须入队;
168+
* 对于某个彩球 $c$ 而言,如果当前棋盘数量少于 3ドル$ 个,那么至少需要补充至 3ドル$ 个才能被消除,而缺少的个数则是「从手上彩球放入棋盘内」的次数,即对于彩球 $c,ドル我们理论上至少需要消耗 3ドル - cnt$ 次($cnt$ 为当前棋盘拥有的彩球 $c$ 的数量)。
169+
170+
需要注意的是:对于某个局面 $node$ 而言,最终的距离是由「已确定距离」+「估值距离」两部分组成,我们应当根据这两部分之和进行出队,才能确保算法的正确性。
171+
172+
![image.png](https://pic.leetcode-cn.com/1636424014-cCaHWU-image.png)
173+
174+
代码:
175+
```Java
176+
class Solution {
177+
class Node {
178+
String a;
179+
int cur, val, step;
180+
Node (String _a, int _c, int _v, int _s) {
181+
a = _a;
182+
cur = _c; val = _v; step = _s;
183+
}
184+
}
185+
int f(String a, int k) {
186+
Map<Character, Integer> m1 = new HashMap<>(), m2 = new HashMap<>();
187+
for (int i = 0; i < a.length(); i++) {
188+
m1.put(a.charAt(i), m1.getOrDefault(a.charAt(i), 0) + 1);
189+
}
190+
for (int i = 0; i < m; i++) {
191+
if (((k >> i) & 1) == 0) m2.put(b.charAt(i), m2.getOrDefault(b.charAt(i), 0) + 1);
192+
}
193+
int ans = 0;
194+
for (char c : m1.keySet()) {
195+
int c1 = m1.get(c), c2 = m2.getOrDefault(c, 0);
196+
if (c1 + c2 < 3) return INF;
197+
if (c1 < 3) ans += (3 - c1);
198+
}
199+
return ans;
200+
}
201+
202+
int INF = 0x3f3f3f3f;
203+
String b;
204+
int m;
205+
Map<String, Integer> map = new HashMap<>();
206+
public int findMinStep(String _a, String _b) {
207+
b = _b;
208+
m = b.length();
209+
PriorityQueue<Node> q = new PriorityQueue<>((o1,o2)->{
210+
return (o1.val + o1.step) - (o2.val + o2.step);
211+
});
212+
q.add(new Node(_a, 1 << m, f(_a, 1 << m), 0));
213+
map.put(_a, 0);
214+
while (!q.isEmpty()) {
215+
Node poll = q.poll();
216+
String a = poll.a;
217+
int cur = poll.cur;
218+
int step = poll.step;
219+
int n = a.length();
220+
for (int i = 0; i < m; i++) {
221+
if (((cur >> i) & 1) == 1) continue;
222+
int next = (1 << i) | cur;
223+
for (int j = 0; j <= n; j++) {
224+
StringBuilder sb = new StringBuilder();
225+
sb.append(a.substring(0, j)).append(b.substring(i, i + 1));
226+
if (j != n) sb.append(a.substring(j));
227+
int k = j;
228+
while (0 <= k && k < sb.length()) {
229+
char c = sb.charAt(k);
230+
int l = k, r = k;
231+
while (l >= 0 && sb.charAt(l) == c) l--;
232+
while (r < sb.length() && sb.charAt(r) == c) r++;
233+
if (r - l - 1 >= 3) {
234+
sb.delete(l + 1, r);
235+
k = l >= 0 ? l : r;
236+
} else {
237+
break;
238+
}
239+
}
240+
String nextStr = sb.toString();
241+
if (nextStr.length() == 0) return step + 1;
242+
if (f(nextStr, next) == INF) continue;
243+
if (!map.containsKey(nextStr) || map.get(nextStr) > step + 1) {
244+
map.put(nextStr, step + 1);
245+
q.add(new Node(nextStr, next, f(nextStr, next), step + 1));
246+
}
247+
}
248+
}
249+
}
250+
return -1;
251+
}
252+
}
253+
```
254+
* 时间复杂度:略。「爆搜」同时还得考虑「启发式加速」的复杂度分析意义不大。
255+
* 空间复杂度:略
256+
257+
---
258+
259+
### 最后
260+
261+
这是我们「刷穿 LeetCode」系列文章的第 `No.488` 篇,系列开始于 2021年01月01日,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
262+
263+
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
264+
265+
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode
266+
267+
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
268+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /