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]
]

第三行开始,每行除边界元素外,每个元素ai都是由ai-1 + ai构成
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> generate(int numRows) {
 3         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 4         if(numRows <= 0)
 5             return res;
 6         ArrayList<Integer> lvl1 = new ArrayList<Integer>();
 7         lvl1.add(1);
 8         res.add(lvl1);
 9         if(numRows == 1)
10             return res;
11         
12         for(int i = 2; i<= numRows; i++){
13             ArrayList<Integer> tmp = new ArrayList<Integer>();
14             for(int j = 0; j<i; j++){
15                 if(j == 0 || j==i-1){
16                     tmp.add(1);
17                 }else{
18                     tmp.add(res.get(res.size()-1).get(j-1)+res.get(res.size()-1).get(j));
19                 }
20             }
21             res.add(tmp);
22         }
23         return res;
24     }
25 }
原文地址:https://www.cnblogs.com/RazerLu/p/3552075.html