LeetCode 题解工作台

杨辉三角

给定一个非负整数 numRows , 生成「杨辉三角」的前 numRows 行。 在 「杨辉三角」 中,每个数是它左上方和右上方的数的和。 示例 1: 输入: numRows = 5 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 示例 2: 输入: nu…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 状态·转移·动态规划

bolt

答案摘要

我们先创建一个答案数组 ,然后将 的第一行元素设为 。接下来,我们从第二行开始,每一行的开头和结尾元素都是 ,其它 $f[i][j] = f[i - 1][j - 1] + f[i - 1][j]$。 时间复杂度 ,其中 为给定的行数。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个非负整数 numRows生成「杨辉三角」的前 numRows 行。

「杨辉三角」中,每个数是它左上方和右上方的数的和。

 

示例 1:

输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

示例 2:

输入: numRows = 1
输出: [[1]]

 

提示:

  • 1 <= numRows <= 30
lightbulb

解题思路

方法一:模拟

我们先创建一个答案数组 ff,然后将 ff 的第一行元素设为 [1][1]。接下来,我们从第二行开始,每一行的开头和结尾元素都是 11,其它 f[i][j]=f[i1][j1]+f[i1][j]f[i][j] = f[i - 1][j - 1] + f[i - 1][j]

时间复杂度 O(n2)O(n^2),其中 nn 为给定的行数。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        f = [[1]]
        for i in range(numRows - 1):
            g = [1] + [a + b for a, b in pairwise(f[-1])] + [1]
            f.append(g)
        return f
speed

复杂度分析

指标
时间complexity is O(numRows^2) because each row i contains i elements, and we compute each sum once. Space complexity is O(numRows^2) if storing all rows, or O(numRows) if only keeping the previous row for computation.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks if you can explain why each element is the sum of the two above.

  • question_mark

    Wants a clear iterative or dynamic programming solution, not recursion.

  • question_mark

    May probe how you handle boundaries or optimize space for large numRows.

warning

常见陷阱

外企场景
  • error

    Forgetting to place 1 at the start and end of each row.

  • error

    Incorrectly summing elements causing off-by-one errors in the triangle.

  • error

    Attempting recursion without memoization, leading to unnecessary complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Generate only the nth row without constructing the full triangle using optimized DP.

  • arrow_right_alt

    Return Pascal's Triangle modulo a given number for very large values.

  • arrow_right_alt

    Compute triangle diagonals or specific positions efficiently using combinatorial formulas.

help

常见问题

外企场景

杨辉三角题解:状态·转移·动态规划 | LeetCode #118 简单