帕斯卡三角

  1. /// ## Paslcal's triangle problem
  2. /// pascal_triangle(num_rows) returns the first num_rows of Pascal's triangle.
  3. /// About Pascal's triangle: https://en.wikipedia.org/wiki/Pascal%27s_triangle
  4. ///
  5. /// Arguments:
  6. /// * `num_rows` - number of rows of triangle
  7. /// Complexity
  8. /// - time complexity: O(n^2),
  9. /// - space complexity: O(n^2),
  10. pub fn pascal_triangle(num_rows: i32) -> Vec<Vec<i32>> {
  11. let mut ans: Vec<Vec<i32>> = vec![];
  12. for i in 1..num_rows + 1 {
  13. let mut vec: Vec<i32> = vec![1];
  14. let mut res: i32 = 1;
  15. for k in 1..i {
  16. res *= i - k;
  17. res /= k;
  18. vec.push(res);
  19. }
  20. ans.push(vec);
  21. }
  22. ans
  23. }
  24. #[cfg(test)]
  25. mod tests {
  26. use super::pascal_triangle;
  27. #[test]
  28. fn test() {
  29. assert_eq!(pascal_triangle(3), vec![vec![1], vec![1, 1], vec![1, 2, 1]]);
  30. assert_eq!(
  31. pascal_triangle(4),
  32. vec![vec![1], vec![1, 1], vec![1, 2, 1], vec![1, 3, 3, 1]]
  33. );
  34. assert_eq!(
  35. pascal_triangle(5),
  36. vec![
  37. vec![1],
  38. vec![1, 1],
  39. vec![1, 2, 1],
  40. vec![1, 3, 3, 1],
  41. vec![1, 4, 6, 4, 1]
  42. ]
  43. );
  44. }
  45. }