mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
简化分支逻辑,如果用了 return 就不用 if else 控制
This commit is contained in:
@ -369,8 +369,44 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
简化分支版本:
|
||||||
|
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
static int ans;
|
||||||
|
public int minCameraCover(TreeNode root) {
|
||||||
|
ans = 0; // 初始化
|
||||||
|
if(f(root) == 0) ans ++;
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
// 定义 f 函数有三种返回值情况
|
||||||
|
// 0:表示 x 节点没有被相机监控,只能依靠父节点放相机
|
||||||
|
// 1:表示 x 节点被相机监控,但相机不是放在自身节点上
|
||||||
|
// 2:表示 x 节点被相机监控,但相机放在自身节点上
|
||||||
|
public static int f(TreeNode x) {
|
||||||
|
if(x == null) return 1; // 空树认为被监控,但没有相机
|
||||||
|
// 左右递归到最深处
|
||||||
|
int l = f(x.left);
|
||||||
|
int r = f(x.right);
|
||||||
|
// 有任意一个子节点为空,就需要当前节点放相机,不然以后没机会
|
||||||
|
if(l == 0 || r == 0) {
|
||||||
|
ans ++; // 放相机
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
// 贪心策略,左右子树都被监控,且没有监控到当前节点,
|
||||||
|
// 那么最有利的情况就是将相机放置在当前节点父节点上,
|
||||||
|
// 因为这样能多监控可能的子树节点和父父节点
|
||||||
|
if(l == 1 && r == 1) return 0;
|
||||||
|
// 剩下情况就是左右子树有可能为 2,即当前节点被监控
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Python
|
### Python
|
||||||
|
|
||||||
贪心(版本一)
|
贪心(版本一)
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
@ -757,4 +793,3 @@ public class Solution
|
|||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user