LeetCode 题解工作台

杨辉三角 II

给定一个非负索引 rowIndex ,返回「杨辉三角」的第 rowIndex 行。 在「杨辉三角」中,每个数是它左上方和右上方的数的和。 示例 1: 输入: rowIndex = 3 输出: [1,3,3,1] 示例 2: 输入: rowIndex = 0 输出: [1] 示例 3: 输入: row…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们创建一个长度为 $rowIndex + 1$ 的数组 ,初始时所有元素均为 。 接下来,我们从第 行开始,从后往前计算当前行的第 个元素的值 $f[j] = f[j] + f[j - 1]$,其中 $j \in [1, i - 1]$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。

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

 

示例 1:

输入: rowIndex = 3
输出: [1,3,3,1]

示例 2:

输入: rowIndex = 0
输出: [1]

示例 3:

输入: rowIndex = 1
输出: [1,1]

 

提示:

  • 0 <= rowIndex <= 33

 

进阶:

你可以优化你的算法到 O(rowIndex) 空间复杂度吗?

lightbulb

解题思路

方法一:递推

我们创建一个长度为 rowIndex+1rowIndex + 1 的数组 ff,初始时所有元素均为 11

接下来,我们从第 22 行开始,从后往前计算当前行的第 jj 个元素的值 f[j]=f[j]+f[j1]f[j] = f[j] + f[j - 1],其中 j[1,i1]j \in [1, i - 1]

最后返回 ff 即可。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n)O(n)。其中 nn 是给定的行数。

1
2
3
4
5
6
7
8
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        f = [1] * (rowIndex + 1)
        for i in range(2, rowIndex + 1):
            for j in range(i - 1, 0, -1):
                f[j] += f[j - 1]
        return f
speed

复杂度分析

指标
时间complexity is O(rowIndex^2) due to nested iteration to update each element, and space complexity is O(rowIndex) because only a single row array is maintained.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can compute only the requested row without building the full triangle.

  • question_mark

    Expect discussion on in-place updates and avoiding overwriting previous row values.

  • question_mark

    Consider edge cases like rowIndex = 0 or rowIndex = 1 to confirm correct base cases.

warning

常见陷阱

外企场景
  • error

    Overwriting elements from left to right, which corrupts intermediate sums.

  • error

    Attempting to build the full Pascal's Triangle when only one row is needed.

  • error

    Ignoring base cases, leading to index out-of-bounds errors or incorrect first row values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the triangle up to rowIndex instead of only one row.

  • arrow_right_alt

    Compute a specific element in rowIndex-th row using combinatorial formula.

  • arrow_right_alt

    Modify the algorithm to handle large rowIndex values efficiently with BigInteger types.

help

常见问题

外企场景

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