From 6bb21c8e5b18ea720651c087ecbe350ffe87a371 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Sat, 3 Jun 2023 11:20:55 +0800 Subject: [PATCH] =?UTF-8?q?Update=200337.=E6=89=93=E5=AE=B6=E5=8A=AB?= =?UTF-8?q?=E8=88=8DIII.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...345\256\266\345\212\253\350\210\215III.md" | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" index ca8cea2369..1708b7a1e8 100644 --- "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" +++ "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" @@ -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>>) -> i32 { + let (v1, v2) = Self::rob_tree(&root); + v1.max(v2) + } + pub fn rob_tree(cur: &Option>>) -> (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, // 偷父节点 + ) + } + } + } +} +```