Back to blog
Nov 19, 2024
2 min read

LeetCode 118: Pascal's Triangle

Leetcode 118: Pascal's Triangle solution in Python

Problem Description

LeetCode Problem 118

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:

 

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

Difficulty: Easy

Tags: array, dynamic programming

Rating: 96.50%

Solution Complexity

The solution has the following complexity characteristics:

  • Time Complexity: O(n²)
  • Space Complexity: O(n)

Note: This is an automated analysis and may not capture all edge cases or specific algorithmic optimizations.

Solution

Here’s my Python solution to this problem:

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0:
            return []
        if numRows == 1:
            return [[1]]
        if numRows == 2:
            return [[1], [1, 1]]
        
        res = [[1], [1, 1]]
        for i in range(2, numRows):
            row = [1]
            for j in range(1, i):
                row.append(res[i-1][j-1] + res[i-1][j])
            row.append(1)
            res.append(row)
        return res