118. 杨辉三角

"""
118. 杨辉三角
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

示例 1:

输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
"""

"""
解题思路:
首位都是lst[0], lst[-1] = 1, 1
该层第j个元素是上一层第j-1和第j个元素的和
lst[j] = ans[i-1][j-1] + ans[i-1][j]
"""

class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
ans = [[1]]
for i in range(1, numRows):
lst = [0 for _ in range(i+1)]
lst[0], lst[-1] = 1, 1
for j in range(1, i):
lst[j] = ans[i-1][j-1] + ans[i-1][j]
ans.append(lst)
return ans

if __name__ == "__main__":
res = Solution().generate(3)
print(res)

posted on 2021-12-14 10:17  random_boy  阅读(19)  评论(0)    收藏  举报

导航