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/

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

1
2
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
solution_test.py
1
2
3
4
5
6
7
8
9
10
11
12
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

solution.py
1
2
3
4
5
6
7
8
9
10
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