20240808 Finished

This commit is contained in:
jackfiled 2024-08-08 11:37:22 +08:00
parent 21cf6e05d6
commit 9b6d2f7d39
2 changed files with 44 additions and 1 deletions

View File

@ -198,3 +198,4 @@ mod p70_climbing_stairs;
mod p198_house_robber;
mod p139_word_break;
mod p300_longest_increasing_subsequence;
mod p120_triangle;

View File

@ -0,0 +1,42 @@
/**
* [120] Triangle
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> 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]]));
}
}