Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 83ca7fc

Browse files
author
ruislan
committed
solved q437
1 parent dfe94cb commit 83ca7fc

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

‎src/q/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ mod q423;
224224
mod q424;
225225
mod q434;
226226
mod q435;
227+
mod q437;
227228
mod q441;
228229
mod q442;
229230
mod q443;

‎src/q/q437.rs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use std::cell::RefCell;
2+
use std::rc::Rc;
3+
4+
use crate::q::Solution;
5+
6+
#[derive(Debug, PartialEq, Eq)]
7+
pub struct TreeNode {
8+
pub val: i32,
9+
pub left: Option<Rc<RefCell<TreeNode>>>,
10+
pub right: Option<Rc<RefCell<TreeNode>>>,
11+
}
12+
13+
#[allow(unused)]
14+
impl TreeNode {
15+
#[inline]
16+
pub fn new(val: i32) -> Self {
17+
TreeNode {
18+
val,
19+
left: None,
20+
right: None,
21+
}
22+
}
23+
}
24+
25+
#[allow(unused)]
26+
impl Solution {
27+
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> i32 {
28+
// 方法1
29+
// dfs
30+
// 每次向下我们都将结果增加1位,然后遍历,如果结果正好等于target,就叠加计数
31+
// AC 0ms 2.2mb 126/126
32+
fn dfs(node: Option<Rc<RefCell<TreeNode>>>, target: i32, path: &mut Vec<i32>) -> i32 {
33+
if let Some(node) = node {
34+
let left = node.borrow_mut().left.take();
35+
let right = node.borrow_mut().right.take();
36+
let val = node.borrow().val;
37+
path.iter_mut().for_each(|x| *x += val);
38+
path.push(val);
39+
let count = path.iter().filter(|&&x| x == target).count() as i32;
40+
41+
let left_count = dfs(left, target, path);
42+
let right_count = dfs(right, target, path);
43+
44+
path.pop();
45+
path.iter_mut().for_each(|x| *x -= val);
46+
return left_count + right_count + count;
47+
}
48+
0
49+
}
50+
dfs(root, target_sum, &mut Vec::new())
51+
}
52+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /