• LeetCode 118. Pascal's Triangle (杨辉三角)


    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    

    题目标签:Array

      题目给了我们一个numRows,让我们写出这个行数的杨辉三角。来观察一下原题例子,5行的话,第一行只有1,第二行,只有1,第三行,除去第一个1和最后一个1,中间的都是上一行的两边数字之和。所以,我们只需要设定,每一行,第一个数字为1,最后一个为1,中间的数字,都由上一行同样位置的数字 + 前一个就可以了。

    Java Solution:

    Runtime beats 19.71% 

    完成日期:04/05/2017

    关键词:Array

    关键点:第一和最后都为1,中间由上一行同样位置数字 + 前一个数字

     1 public class Solution 
     2 {
     3     public List<List<Integer>> generate(int numRows) 
     4     {
     5         
     6         List<List<Integer>> pt = new ArrayList<>();
     7         
     8         // create numRows List.
     9         for(int i=0; i < numRows; i++)
    10         {
    11             List<Integer> list = new ArrayList<>();
    12             //    each row's first and last element is 1.
    13             for(int j=0; j <= i; j++)
    14             {
    15                 if(j == 0)
    16                     list.add(1);
    17                 else if(j == i)
    18                     list.add(1);
    19                 else    // the middle element is sum of last row's same index-1 and index.
    20                     list.add( pt.get(i-1).get(j-1) + pt.get(i-1).get(j) );
    21                 
    22             }
    23             
    24             
    25             pt.add(list);    // add this row into pt.
    26         }
    27         
    28         
    29         return pt;
    30     }
    31 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    软件工程实践2020_个人作业 —— 软件评测
    软件工程实践2020_结对第二次作业 —— 某次疫情统计可视化的实现
    最受欢迎的 Git 分支工作流
    结对编程作业
    软件案例分析作业
    个人项目
    个人博客作业1
    第一次作业-热身!
    面向对象第三单元
    电梯作业总结
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7439848.html
Copyright © 2020-2023  润新知