118.杨辉三角


118.杨辉三角

给定一个非负整数 numRows生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

img

示例 1:

输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

示例 2:

输入: numRows = 1
输出: [[1]]

提示:

  • 1 <= numRows <= 30

题解:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> yanghui = new ArrayList<>();
        for (int row = 0; row < numRows; row++) {
            ArrayList<Integer> rows = new ArrayList<>();
            // 每行的第一个数字必定是1
            rows.add(1);
            // 从第2行起(从0开始算),每行除了第一个和最后一个的元素都是上一行的[row-1][col-1]元素加上上一行的[row-1][col]元素
            for (int col = 1; col <= row - 1; col++) {
                rows.add(yanghui.get(row - 1).get(col - 1) + yanghui.get(row - 1).get(col));
            }
            // 每行的最后一个数字必定是1
            if (row != 0) {
                rows.add(1);
            }
            yanghui.add(rows);
        }
        return yanghui;
    }
}

文章作者: Feliks
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Feliks !
评论
  目录