Skip to content

Commit

Permalink
add minimum-falling-path-sum but time limit exceed
Browse files Browse the repository at this point in the history
  • Loading branch information
pymongo committed Jan 23, 2024
1 parent 0748d0f commit 9301cb7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/dp/minimum_falling_path_sum.rs
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);
}
}
1 change: 1 addition & 0 deletions src/dp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ mod stone_game;
mod trapping_rain_water;
mod triangle;
mod unique_paths;
mod minimum_falling_path_sum;

0 comments on commit 9301cb7

Please sign in to comment.