feat: 120_triangle

This commit is contained in:
SquidSpirit 2025-09-25 21:23:26 +08:00
parent 50189b8aca
commit 493b9c50c5
3 changed files with 50 additions and 0 deletions

7
120_triangle/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "triangle"
version = "0.1.0"

6
120_triangle/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "triangle"
version = "0.1.0"
edition = "2024"
[dependencies]

37
120_triangle/src/lib.rs Normal file
View File

@ -0,0 +1,37 @@
pub struct Solution;
impl Solution {
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
let mut sums = vec![i32::MAX; triangle.len()];
sums[0] = triangle[0][0];
for (layer, nums) in triangle.iter().enumerate() {
if layer == 0 {
continue;
}
let mut current_sums = vec![];
for (index, num) in nums[..layer + 1].iter().enumerate() {
let left = if index == 0 {
i32::MAX
} else {
sums[index - 1]
};
let right = if index == layer {
i32::MAX
} else {
sums[index]
};
current_sums.push(*num + std::cmp::min(left, right));
}
for (index, sum) in current_sums.iter().enumerate() {
sums[index] = *sum;
}
}
*sums.iter().min().unwrap()
}
}