GoCalf Calf 的自留地 · 昙花一现

118. Pascal’s Triangle

Problem

Given an integer numRows, return the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

https://leetcode.cn/problems/pascals-triangle/

pascal
pascal

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

Test Cases

python
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
solution_test.py下载完整源码
py
import pytest

from solution import Solution


@pytest.mark.parametrize('numRows, expected', [
    (5, [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]),
    (1, [[1]]),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, numRows, expected):
    assert sol.generate(numRows) == expected

Thoughts

直接用 119. Pascal’s Triangle II 中组合数的递推方式计算整个杨辉三角即可。

Code

py
class Solution:
    def generate(self, numRows: int) -> list[list[int]]:
        res = [[1]]
        for n in range(1, numRows):
            row = [1] * (n + 1)
            for m in range(1, n // 2 + 1):
                row[m] = row[n - m] = row[m - 1] * (n - m + 1) // m
            res.append(row)

        return res

评论需要 JavaScript。