⚡Flashcard Drill➔
NeetCode #41LC-118EasyArrays & Hashing
← Back to All Problems

#41 · #118 · Pascal's Triangle(杨辉三角)

📌 Problem Statement & Constraints

Given an integer numRows, return the first numRows rows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Constraints: 1 <= numRows <= 30.

💡 Core Algorithmic Approaches

  1. Every row starts and ends with 1.
  2. Interior elements are the sum of the previous row's adjacent pairs: row[j] = prev[j-1] + prev[j].
  3. Build each row from the previous one, so the work per row is proportional to its length.
  4. The total number of elements is numRows * (numRows + 1) / 2, which sets both the time and space bounds.

💻 Benchmark Python3 Implementation

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res = [[1]]                        # row 0
        for _ in range(1, numRows):
            prev = res[-1]
            row = [1]
            for j in range(1, len(prev)):
                row.append(prev[j - 1] + prev[j])   # interior sums
            row.append(1)
            res.append(row)
        return res


# Same idea, written with the classic boundary padding
class Solution2:
    def generate(self, numRows: int) -> List[List[int]]:
        res = []
        for i in range(numRows):
            row = [1] * (i + 1)
            for j in range(1, i):
                row[j] = res[i - 1][j - 1] + res[i - 1][j]
            res.append(row)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(numRows^2): the total number of generated elements is quadratic in numRows.
💾 Space Complexity
O(numRows^2) for the returned triangle, which is unavoidable since the output itself is that large.

⚠️ Interview Pitfalls & Follow-ups

  • Building rows of the wrong length: row i has exactly i + 1 elements.
  • Using the current row instead of the previous row for the sums: row[j] must read from res[i-1], otherwise the already-updated values contaminate the result.
  • Indexing prev[j+1] for the last interior element: the last element of the previous row is prev[-1], and the interior loop must stop before it.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

杨辉三角

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。在杨辉三角中,每个数是它左上方和右上方的数之和。约束:1 ≤ numRows ≤ 30。

核心要点

  • 逐行构造(标准解) :第一行为 [1]。之后每一行的首尾都是 1,中间第 k 个元素等于上一行第 k-1 与第 k 个元素之和。
  • 递推公式 : row[k] = prev[k-1] + prev[k] ,其中 k 从 1 到 len(prev)-1。
  • 构造技巧 : [1] + [prev[k] + prev[k+1] for k in range(len(prev)-1)] + [1] ,一行完成。
  • 复杂度分析 :前 n 行共 n(n+1)/2 个元素,因此时间与空间都是 O(n²),这是输出本身规模决定的,无法优化。

常见陷阱

  • 中间元素的求和下标写错 : prev[k] + prev[k+1] 对应的是「左上方 + 右上方」,若写成 prev[k-1] + prev[k] 并配错循环范围会越界或错位。
  • 忘记首尾的 1 :只算中间元素会导致每行长度少 2。
  • numRows == 1 的边界 :循环 range(1, 1) 不执行,直接返回 [[1]],本解正确;若写法依赖「上一行存在」则需注意。
  • 误答空间复杂度 O(1) :即使逐行覆盖,输出本身是 O(n²),必须计入。

参考实现

class Solution:
    def generate(self, numRows: int) -> list[list[int]]:
        res = [[1]]
        for _ in range(1, numRows):
            prev = res[-1]
            row = [1] + [prev[k] + prev[k + 1] for k in range(len(prev) - 1)] + [1]
            res.append(row)
        return res