Leetcode 题目解析之 Pascal's Triangle

2022-01-09 11:41:51 浏览数 (1)

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return

[

代码语言:txt复制
 [1],
代码语言:txt复制
[1,1],

1,2,1,

1,3,3,1,

1,4,6,4,1

]

代码语言:txt复制
    public List<List<Integer>> generate(int numRows) {
        ArrayList<List<Integer>> rt = new ArrayList<List<Integer>>();
        Integer[] pre = null;
        for (int i = 1; i <= numRows; i  ) {
            //must be defined as Integer[]
            Integer[] row = new Integer[i];
            row[0] = 1;
            row[i - 1] = 1;
            for (int j = 1; j < i - 1; j  ) {
                row[j] = pre[j]   pre[j - 1];
            }
            rt.add(new ArrayList<Integer>(Arrays.asList(row)));
            pre = row;
        }
        return rt;
    }

0 人点赞