118. Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 1 public class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> listAll = new ArrayList<>();
 4         if (numRows <= 0) return listAll;
 5         for (int i = 0; i < numRows; i++) {
 6             List<Integer> list = new ArrayList<>();
 7             list.add(1);
 8             if (i != 0) {
 9                 List<Integer> prevList = listAll.get(i - 1);
10                 for (int j = 1; j < prevList.size(); j++) {
11                     list.add(prevList.get(j-1) + prevList.get(j));
12                 }
13                 list.add(1);
14             }
15             listAll.add(list);
16         }
17         return listAll;   
18     }
19 }

 

posted @ 2019-04-28 11:36  北叶青藤  阅读(117)  评论(0编辑  收藏  举报