فهرست منبع

feat: triangle

Zhang Li 1 سال پیش
والد
کامیت
cf44899660
2فایلهای تغییر یافته به همراه59 افزوده شده و 1 حذف شده
  1. 2 1
      src/solutions/array/mod.rs
  2. 57 0
      src/solutions/array/triangle.rs

+ 2 - 1
src/solutions/array/mod.rs

@@ -9,4 +9,5 @@ mod sort_colors;
 mod remove_duplicate_from_sorted_array2;
 mod merge_sorted_array;
 mod pascal_triangle;
-mod pascal_triangle2;
+mod pascal_triangle2;
+mod triangle;

+ 57 - 0
src/solutions/array/triangle.rs

@@ -0,0 +1,57 @@
+struct Solution;
+
+
+impl Solution {
+    pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
+        let mut res = i32::MAX;
+        let l = triangle.len();
+
+        let mut v = vec![0;l];
+        for i in 0..l {
+            let cols = triangle[i].len();
+            if i == 0 {
+                v[0] = triangle[0][0];
+                res = v[0];
+            } else {
+                for j in (0..cols).rev() {
+                    if j == 0 {
+                        v[0] = v[0] + triangle[i][0];
+                    } else if j==i {
+                        v[j] = v[j-1] + triangle[i][i];
+                        res = v[i];
+                    } else {
+                        v[j] = (v[j] + triangle[i][j]).min(v[j-1] + triangle[i][j]);
+                    }
+                    res = res.min(v[j]);
+                }
+            }
+
+
+
+            // println!("v: {:?}", v);
+        }
+        res
+
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+
+    use super::*;
+
+    #[test]
+    fn test_minimum_total() {
+        let triangle = vec![vec![2],vec![3,4],vec![6,5,7],vec![4,1,8,3]];
+        let res = Solution::minimum_total(triangle);
+        assert_eq!(res, 11);
+    }
+
+    #[test]
+    fn test_minimum_total1() {
+        let triangle = vec![vec![-7],vec![-2,1],vec![-5,-5,9],vec![-4,-5,4,4],vec![-6,-6,2,-1,-5],vec![3,7,8,-3,7,-9],vec![-9,-1,-9,6,9,0,7],vec![-7,0,-6,-8,7,1,-4,9],vec![-3,2,-6,-9,-7,-6,-9,4,0],vec![-8,-6,-3,-9,-2,-6,7,-5,0,7],vec![-9,-1,-2,4,-2,4,4,-1,2,-5,5],vec![1,1,-6,1,-2,-4,4,-2,6,-6,0,6],vec![-3,-3,-6,-2,-6,-2,7,-9,-5,-7,-5,5,1]];
+        let res = Solution::minimum_total(triangle);
+        assert_eq!(res, -63);
+    }
+}