力扣: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
相关推荐
JieE2128 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵13 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1118 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0020 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent