Skip to content

Commit

Permalink
Update 0337.打家劫舍III.md about rust
Browse files Browse the repository at this point in the history
  • Loading branch information
fwqaaq authored Jun 3, 2023
1 parent 4ab224b commit 6bb21c8
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions problems/0337.打家劫舍III.md
Original file line number Diff line number Diff line change
Expand Up @@ -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">
Expand Down

0 comments on commit 6bb21c8

Please sign in to comment.