力扣: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
相关推荐
BK贝壳1 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon5 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw5 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn5 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern098 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980119 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
民乐团扒谱机11 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T11 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
databook11 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析