118. Pascal's Triangle

Total Accepted: 73821
Total Submissions: 227589
Difficulty: Easy

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

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> row, pre = null;
        for (int i = 0; i < numRows; ++i) {
            row = new ArrayList<Integer>();
            for (int j = 0; j <= i; ++j)
                if (j == 0 || j == i)
                    row.add(1);
                else
                    row.add(pre.get(j - 1) + pre.get(j));
            pre = row;
            res.add(row);
        }
        return res;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。