mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Update 0337.打家劫舍III.md about rust
This commit is contained in:
@ -490,6 +490,33 @@ function robNode(node: TreeNode | null): MaxValueArr {
|
||||
}
|
||||
```
|
||||
|
||||
### Rust
|
||||
|
||||
动态规划:
|
||||
|
||||
```rust
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
impl Solution {
|
||||
pub fn rob(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||
let (v1, v2) = Self::rob_tree(&root);
|
||||
v1.max(v2)
|
||||
}
|
||||
pub fn rob_tree(cur: &Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
|
||||
match cur {
|
||||
None => (0, 0),
|
||||
Some(node) => {
|
||||
let left = Self::rob_tree(&node.borrow_mut().left);
|
||||
let right = Self::rob_tree(&node.borrow_mut().right);
|
||||
(
|
||||
left.0.max(left.1) + right.0.max(right.1), // 偷左右节点
|
||||
node.borrow().val + left.0 + right.0, // 偷父节点
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
|
Reference in New Issue
Block a user