From 1c46d51b5f6d5b66abe455e4689c194556aec23c Mon Sep 17 00:00:00 2001 From: li-chx Date: Thu, 13 Aug 2026 17:38:13 +0800 Subject: [PATCH] =?UTF-8?q?124.=20=E4=BA=8C=E5=8F=89=E6=A0=91=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E8=B7=AF=E5=BE=84=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 32 +++++++++++++++++++------------- src/tree.rs | 14 +++++++++++++- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1a52487..b7fbd63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,24 +1,30 @@ mod arr; +mod tree; + +use crate::tree::{TreeNode, build_tree_from_str}; struct Solution {} +use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { - let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1]; - let text1 = text1.chars().collect::>(); - let text2 = text2.chars().collect::>(); - for i in 0..text1.len() { - for j in 0..text2.len() { - dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]); - if text1[i] == text2[j] { - dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 1); - } - } + pub fn max_path_sum(root: Option>>) -> i32 { + let (_,ans) = Self::dfs(&root); + ans + } + fn dfs(root: &Option>>) -> (i32, i32) { + if root.is_none() { + return (-100000000, -100000000); } - dp[text1.len()][text2.len()] + let (la, ln) = Self::dfs(&root.as_ref().unwrap().borrow().left); + let (ra, rn) = Self::dfs(&root.as_ref().unwrap().borrow().right); + let val = root.as_ref().unwrap().borrow().val; + let a = val.max(val + la).max(val + ra); + let n = a.max(ln).max(rn).max(val + la + ra); + (a, n) } } fn main() { println!( "{:?}", - Solution::longest_common_subsequence("abcde".to_string(), "ace".to_string()) + Solution::max_path_sum(build_tree_from_str("[5,4,8,11,null,13,4,7,2,null,null,null,1]")) ); } diff --git a/src/tree.rs b/src/tree.rs index 7179452..a41fe06 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -15,7 +15,19 @@ impl TreeNode { TreeNode { val, left: None, right: None } } } - +pub fn build_tree_from_str(s: &str) -> Option>> { + // [-10,9,20,null,null,15,7] + let s = s.trim_matches(&['[', ']'][..]).split(',').map(|x| x.trim()).collect::>(); + let mut vals = vec![]; + for x in s { + if x == "null" { + vals.push(None); + }else { + vals.push(Some(i32::from_str_radix(x, 10).unwrap())); + } + } + build_tree(&vals) +} pub fn build_tree(vals: &[Option]) -> Option>> { if vals.is_empty() || vals[0].is_none() { return None;