Leetcode 118. 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]
]

题意:给出一个数字,生成该数字对应的一个杨辉三角。

思路:
观察题目给出的例子,每一层首尾值是1,其余位置i的值是上一层i和i-1位置的和。
第一层可以先初始化好,之后在计算每层各个位置的值时,只需要取出上一层i和i-1位置的值算出来即可。

public List> generate(int numRows) {
    List> res = new ArrayList<>();
    if (numRows < 1) {
        return res;
    }

    List l1 = new ArrayList<>();
    l1.add(1);
    res.add(l1);
    for (int i = 1; i < numRows; i++) {
        List pre = res.get(i - 1);
        List cur = new ArrayList<>();
        for (int j = 0; j <= pre.size(); j++) {
            if (j == 0 || j == pre.size()) {
                cur.add(1);
            } else {
                cur.add(pre.get(i - 1) + pre.get(i));
            }
        }
        res.add(cur);
    }

    return res;
}

你可能感兴趣的:(Leetcode 118. Pascal's Triangle)