Browse Source

feat: pascal_triangle2

Zhang Li 1 year ago
parent
commit
c66c725bab
2 changed files with 46 additions and 0 deletions
  1. 1 0
      src/solutions/array/mod.rs
  2. 45 0
      src/solutions/array/pascal_triangle2.rs

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

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

+ 45 - 0
src/solutions/array/pascal_triangle2.rs

@@ -0,0 +1,45 @@
+struct Solution;
+
+impl Solution {
+    pub fn get_row(row_index: i32) -> Vec<i32> {
+        let mut res = vec![1];
+        let mut prev: i64 = 1;  // use i64 for the calculations
+        for k in 1..=row_index {
+            let next_val = prev * (row_index - k + 1) as i64 / k as i64;
+            res.push(next_val as i32);
+            prev = next_val;
+        }
+        res
+
+    }
+
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+
+    #[test]
+    fn test_get_row() {
+        let row_index = 4;
+        let res = Solution::get_row(row_index);
+        assert_eq!(res, vec![1,4,6,4,1]);
+    }
+
+    #[test]
+    fn test_get_row1() {
+        let row_index = 13;
+        let res = Solution::get_row(row_index);
+        assert_eq!(res, vec![1,13,78,286,715,1287,1716,1716,1287,715,286,78,13,1]);
+    }
+
+
+    #[test]
+    fn test_get_row2() {
+        let row_index = 21;
+        let res = Solution::get_row(row_index);
+        assert_eq!(res, vec![1,21,210,1330,5985,20349,54264,116280,203490,293930,352716,352716,293930,203490,116280,54264,20349,5985,1330,210,21,1]);
+    }
+
+}