题目:
给定一个非负整数
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得到。
代码:
pythonclass 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
力扣:118. 杨辉三角(Python3)
恽劼恒2023-10-03 20:04
相关推荐
BK贝壳1 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码BD_Marathon5 小时前
安装Jupyter notebookZlzxzw5 小时前
End-to-End Autonomous Generation of Human Assembly PlansWellijohn5 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍Logintern098 小时前
deep agents 多智能体模式——规划与委派2601_967980119 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值民乐团扒谱机11 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界饮水桶_T11 小时前
C++ stack & queue复习笔记databook11 小时前
时间序列预测,模型换了一圈为什么没变好