当前位置:   article > 正文

leetcode简单题26 N.118 杨辉三角 rust描述

leetcode简单题26 N.118 杨辉三角 rust描述


 

  1. // 动态规划
  2. pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {
  3. let mut triangle: Vec<Vec<i32>> = vec![];
  4. for i in 0..num_rows {
  5. let mut row = vec![1; (i + 1) as usize];
  6. for j in 1..i as usize {
  7. row[j] = triangle[(i - 1) as usize][(j - 1)] + triangle[(i - 1) as usize][j];
  8. }
  9. triangle.push(row);
  10. }
  11. triangle
  12. }
  13. use std::collections::HashMap;
  14. // 递归(带缓存)
  15. struct Solution;
  16. impl Solution {
  17. pub fn generate(num_rows: i32) -> Vec<Vec<i32>> {
  18. let mut cache = HashMap::new();
  19. let mut triangle = vec![];
  20. for i in 0..num_rows {
  21. let mut row = vec![];
  22. for j in 0..=i {
  23. row.push(Self::get_value(i, j, &mut cache));
  24. }
  25. triangle.push(row);
  26. }
  27. triangle
  28. }
  29. fn get_value(i: i32, j: i32, cache: &mut HashMap<(i32, i32), i32>) -> i32 {
  30. if j == 0 || j == i {
  31. return 1;
  32. }
  33. if let Some(&val) = cache.get(&(i, j)) {
  34. return val;
  35. }
  36. let val = Self::get_value(i - 1, j - 1, cache) + Self::get_value(i - 1, j, cache);
  37. cache.insert((i, j), val);
  38. val
  39. }
  40. }
  41. // 迭代
  42. pub fn generate2(num_rows: i32) -> Vec<Vec<i32>> {
  43. let mut triangle: Vec<Vec<i32>> = Vec::with_capacity(num_rows as usize);
  44. for i in 0..num_rows as usize {
  45. let mut row = vec![1; i + 1];
  46. for j in 1..i {
  47. row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
  48. }
  49. triangle.push(row);
  50. }
  51. triangle
  52. }
  53. fn main() {}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/859562
推荐阅读
相关标签
  

闽ICP备14008679号