Problem
Given an integernumRows, 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:
Examples
Constraints
- 1 <= numRows <= 30
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 118 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 118 # by problem number
lcpy gen -s pascals_triangle # by problem name
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:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Input: numRows = 1
Output: [[1]]
class Solution:
# Time: O(n^2)
# Space: O(1) excluding output
def generate(self, num_rows: int) -> list[list[int]]:
triangle: list[list[int]] = [[1]]
for _ in range(1, num_rows):
previous = triangle[-1]
row = [1] + [previous[i] + previous[i + 1] for i in range(len(previous) - 1)] + [1]
triangle.append(row)
return triangle
| Time | Space |
|---|---|
| O(n^2) | O(1) excluding output |