跳转至

118.pascals-triangle

Statement

Metadata
  • Link: 杨辉三角
  • Difficulty: Easy
  • Tag: 数组 动态规划

给定一个非负整数 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

Metadata

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

Solution

from typing import List


class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res = [[1]]
        pre = res[0]
        for _ in range(numRows - 1):
            cur_res = [1]

            for i in range(len(pre) - 1):
                cur_res.append(pre[i] + pre[i + 1])

            cur_res.append(1)
            res.append(cur_res)
            pre = cur_res
        return res

最后更新: October 11, 2023
回到页面顶部