-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add minimum-falling-path-sum but time limit exceed
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
//! https://leetcode.cn/problems/minimum-falling-path-sum | ||
fn min_falling_path_sum(matrix: Vec<Vec<i32>>) -> i32 { | ||
let m = matrix.len(); | ||
let n = matrix[0].len(); | ||
|
||
let mut min = i32::MAX; | ||
for j in 0..n { | ||
min = min.min(search(0, j, m, n, 0, &matrix)); | ||
} | ||
|
||
min | ||
} | ||
|
||
fn search(row: usize, col:usize, m: usize, n: usize, mut sum: i32, matrix: &Vec<Vec<i32>>) -> i32 { | ||
if row == m { | ||
return sum; | ||
} | ||
let cur_val = matrix[row][col]; | ||
sum += cur_val; | ||
let mut min = search(row+1,col, m, n, sum, matrix); | ||
if col >= 1 { | ||
min = min.min(search(row+1,col-1, m, n, sum, matrix)); | ||
} | ||
if col < n-1 { | ||
min = min.min(search(row+1,col+1, m, n, sum, matrix)); | ||
} | ||
min | ||
} | ||
|
||
#[test] | ||
fn test() { | ||
for (matrix, min_path_sum) in [ | ||
( | ||
vec_vec![ | ||
[-19,57],[-40,-5] | ||
], | ||
-59 | ||
), | ||
( | ||
vec_vec![ | ||
[2,1,3],[6,5,4],[7,8,9] | ||
], | ||
13 | ||
) | ||
] { | ||
assert_eq!(min_falling_path_sum(matrix), min_path_sum); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,3 +34,4 @@ mod stone_game; | |
mod trapping_rain_water; | ||
mod triangle; | ||
mod unique_paths; | ||
mod minimum_falling_path_sum; |