Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2121 from fwqaaq/patch-35
Browse files Browse the repository at this point in the history
Update 0337.打家劫舍III.md about rust
  • Loading branch information
youngyangyang04 authored Jun 21, 2023
2 parents 397b176 + 6bb21c8 commit d1c1e4b
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 d1c1e4b

Please sign in to comment.