File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,27 @@ func backtrack(选择列表,路径):
21
21
22
22
核心就是从选择列表里做一个选择,然后一直递归往下搜索答案,如果遇到路径不通,就返回来撤销这次选择。
23
23
24
+ ### 搜到一个解就提前终止搜索、返回结果的模板 [ lc473.火柴拼正方形] ( https://leetcode.cn/problems/matchsticks-to-square/ )
25
+ ``` python
26
+ # 似乎只能搜索
27
+ matchsticks.sort(reverse = True ) # 从大到小,这样提前爆大、被剪枝
28
+ sums = [0 ] * 4
29
+ def backtrack (i ):
30
+ if max (sums) > edge:
31
+ return # 终止搜索子树,但其实 if sums[pile_id] <= edge就有保证
32
+ if i == n: # 搜到叶子节点
33
+ if all (s == edge for s in sums):
34
+ return True
35
+ for pile_id in range (4 ):
36
+ sums[pile_id] += matchsticks[i]
37
+ if sums[pile_id] <= edge and backtrack(i + 1 ): # 这里递归调用,利用返回值
38
+ return True
39
+ sums[pile_id] -= matchsticks[i]
40
+ return False
41
+
42
+ return backtrack(0 )
43
+ ```
44
+
24
45
## 示例
25
46
26
47
### [ subsets] ( https://leetcode-cn.com/problems/subsets/ )
You can’t perform that action at this time.
0 commit comments