力扣:118. 杨辉三角(Python3)

题目:

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

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

来源:力扣(LeetCode)

链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:numRows = 5

输出:0,1

解释:\[1,1,1,1,2,1,1,3,3,1,1,4,6,4,1]

示例 2:

输入:numRows = 1

输出:\[1]

解法:

寻找规律:

1, 1\] = \[0, 1\] + \[1, 0

1, 2, 1\] = \[0, 1, 1\] + \[1, 1, 0

1, 3, 3, 1\] = \[0, 1, 2, 1\] + \[1, 2, 1, 0

1, 4, 6, 4, 1\] = \[0, 1, 3, 3, 1\] + \[1, 3, 3, 1, 0

所以第i行=第i-1行左添0+右添0得到。

代码:

python 复制代码
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        result = []
        n = [1]
        for _ in range(numRows):
            result.append(n)
            n = [x + y for x, y in zip([0] + n, n + [0])]
        return result
相关推荐
皓月斯语1 分钟前
P2858 [USACO06FEB] Treats for the Cows G/S
数据结构·c++·算法·动态规划
旖旎夜光10 分钟前
LeetCode 397:整数替换(贪心问题) —— 题解
数据结构·c++·算法·leetcode·贪心算法
奈斯先生Vector14 分钟前
2026 开发者效能革命:基于创源AIGC 与开源生态的工程化实践、安全沙箱与代码智能体协同
人工智能·算法·架构·prompt·aigc
事缓则圆14 分钟前
从零推导 Python 装饰器:不用背语法,看完这篇就懂了
python
鬼手点金17 分钟前
Hermes‑Agent 使用教程
python·ubuntu·powershell·cmd·ai agent·opencode·hermes
Gu Gu Study20 分钟前
【agent认知】宏观Agent的基本两层架构(Agent Loop与Agent Harness)
python·架构
从小就看凹凸曼^o^23 分钟前
Python基础3 - 流程控制语句:(1)程序结构
python
Sagittarius_A*25 分钟前
哈希与认证基础(一):哈希函数的安全目标:原像、第二原像与碰撞
算法·安全·信息安全·密码学·哈希算法
小陈的进阶之路1 小时前
爬虫三大解析库:lxml, jsonpath, bs4
开发语言·笔记·python
满怀冰雪1 小时前
17-正则化方法:Dropout、权重衰减与过拟合控制
人工智能·python·深度学习·机器学习·paddlepaddle