跳转至

118. Pascals Triangle

Leetcode Array

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

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

分析

杨辉三角。考查基本的矩阵操作。根据动画中的步骤,一层一层构建矩阵。

public List<List<Integer>> generate(int numRows) {
    List<List<Integer>> res = new ArrayList<>();
    for (int i = 0; i < numRows; i++) {
        List<Integer> list = new ArrayList<>(), prev = null;
        if (i > 0) prev = res.get(i - 1);
        for (int j = 0; j <= i; j++) {
            if (j == 0 || j == i) list.add(1);
            else list.add(prev.get(j-1) + prev.get(j));
        }
        res.add(list);
    }
    return res;
}