题目:
给定一个非负整数
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
相关推荐
笨笨聊运维2 小时前
CentOS官方不维护版本,配置python升级方法,无损版Gerardisite2 小时前
如何在微信个人号开发中有效管理API接口?小毛驴8503 小时前
软件设计模式-装饰器模式gfdhy3 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用闲人编程3 小时前
Python的导入系统:模块查找、加载和缓存机制百***06013 小时前
SpringMVC 请求参数接收weixin_457760003 小时前
Python 数据结构一个不知名程序员www4 小时前
算法学习入门---vector(C++)合作小小程序员小小店4 小时前
web网页,在线%抖音,舆情,线性回归%分析系统demo,基于python+web+echart+nlp+线性回归,训练,数据库mysql