diff --git a/src/problem/mod.rs b/src/problem/mod.rs index c83ed68..1d707b1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -197,4 +197,5 @@ mod p149_max_points_on_a_line; mod p70_climbing_stairs; mod p198_house_robber; mod p139_word_break; -mod p300_longest_increasing_subsequence; \ No newline at end of file +mod p300_longest_increasing_subsequence; +mod p120_triangle; \ No newline at end of file diff --git a/src/problem/p120_triangle.rs b/src/problem/p120_triangle.rs new file mode 100644 index 0000000..e94d3f9 --- /dev/null +++ b/src/problem/p120_triangle.rs @@ -0,0 +1,42 @@ +/** + * [120] Triangle + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn minimum_total(triangle: Vec>) -> i32 { + let n = triangle.len(); + let mut dp = vec![i32::MAX; n]; + dp[0] = 0; + + for i in 0..n { + let mut next_dp = vec![i32::MAX; n]; + for j in 0..=i { + if j == 0 { + next_dp[j] = triangle[i][j] + dp[j]; + } else { + next_dp[j] = triangle[i][j] + dp[j - 1].min(dp[j]); + } + } + + dp = next_dp; + } + + *dp.iter().min().unwrap() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_120() { + assert_eq!(11, Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]])); + } +}