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

 

posted @ 2017-08-27 11:06  Jimmy_Cheng  阅读(321)  评论(0编辑  收藏  举报