1. 程式人生 > >LeetCode 118. Pascal's Triangle (楊輝三角)

LeetCode 118. Pascal's Triangle (楊輝三角)

== pascal else 只需要 first [1] blog 日期 都是

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

LeetCode 118. Pascal's Triangle (楊輝三角)