From 7fab5209044cf29c0f7db8f7d0b35fddf19fd011 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 9 Aug 2024 11:07:47 +0800 Subject: [PATCH] 20240809 Finished --- src/problem/mod.rs | 3 +- src/problem/p64_minimum_path_sum.rs | 46 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/problem/p64_minimum_path_sum.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1d707b1..fbe5460 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -198,4 +198,5 @@ mod p70_climbing_stairs; mod p198_house_robber; mod p139_word_break; mod p300_longest_increasing_subsequence; -mod p120_triangle; \ No newline at end of file +mod p120_triangle; +mod p64_minimum_path_sum; \ No newline at end of file diff --git a/src/problem/p64_minimum_path_sum.rs b/src/problem/p64_minimum_path_sum.rs new file mode 100644 index 0000000..fd10750 --- /dev/null +++ b/src/problem/p64_minimum_path_sum.rs @@ -0,0 +1,46 @@ +/** + * [64] Minimum Path Sum + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn min_path_sum(grid: Vec>) -> i32 { + let (m, n) = (grid.len(), grid[0].len()); + let mut dp = vec![vec![0; n]; m]; + + for i in 0..m { + for j in 0..n { + if i == 0 { + if j == 0 { + dp[i][j] = grid[i][j]; + } else { + dp[i][j] = dp[i][j - 1] + grid[i][j]; + } + } else { + if j == 0 { + dp[i][j] = dp[i - 1][j] + grid[i][j]; + } else { + dp[i][j] = dp[i - 1][j].min(dp[i][j - 1]) + grid[i][j]; + } + } + } + } + + dp[m - 1][n - 1] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_64() { + assert_eq!(7, Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]])); + } +}