题目:
给定一个非负整数
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
相关推荐
小帅热爱难回头20 分钟前
编写Skill生成AI落地项目系统架构diving deep1 小时前
脚本速览-python2601_951643772 小时前
Python第一,Java跌出前三,C语言杀回来了AC赳赳老秦4 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源一只齐刘海的猫5 小时前
【Leetcode】找到字符串中所有字母异位词海清河晏1115 小时前
数据结构 | 八大排序IronMurphy6 小时前
【算法五十七】146. LRU 缓存茉莉玫瑰花茶6 小时前
综合案例 - AI 智能租房助手 [ 5 ]文艺倾年6 小时前
【强化学习】强化学习基本概念,20W字总结(一)