#8217;s Triangle

友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

118. Pascal’s Triangle

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

PascalTriangleAnimated2

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]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Pascal's Triangle.
 *
 * Memory Usage: 34 MB, less than 7.23% of Java online submissions for Pascal's Triangle.
 */
public List<List<Integer>> generate(int numRows) {
    if (numRows < 1) {
        return Collections.emptyList();
    }
    List<List<Integer>> result = new ArrayList<>(numRows);
    result.add(Arrays.asList(1));
    for (int i = 1; i < numRows; i++) {
        List<Integer> parent = result.get(i - 1);
        int length = parent.size() + 1;
        List<Integer> current = new ArrayList<>(length);
        current.add(1);
        for (int j = 1; j < length; j++) {
            int left = parent.get(j - 1);
            int right = j >= parent.size() ? 0 : parent.get(j);
            current.add(left + right);
        }
        result.add(current);
    }

    return result;
}