leetcode 118 杨辉三角 python
2021-05-19 09:28
标签:python yield range span color 生成 pytho etc class leetcode 118 杨辉三角 python 标签:python yield range span color 生成 pytho etc class 原文地址:https://www.cnblogs.com/feyfree/p/9743186.html杨辉三角 一开始自己使用的方法
1 class Solution:
2 def generate(self, numRows):
3 """
4 :type numRows: int
5 :rtype: List[List[int]]
6 """
7 if numRows == 0:
8 return []
9 elif numRows == 1:
10 return [[1]]
11 elif numRows == 2:
12 return [[1], [1, 1]]
13 else:
14 triangle = [[1],[1,1]]
15 for i in range(2, numRows):
16 triangle.append([])
17 triangle[i].append(1)
18 for j in range(1, i):
19 triangle[i].append(triangle[i - 1][j - 1] + triangle[i - 1][j])
20 triangle[i].append(1)
21 return triangle
了解了python的生成器后重写了一下class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
def rowGenerator():
row = [1]
while True:
yield(row)
row = [1] + [row[k] + row[k + 1] for k in range(len(row) - 1)] + [1]
listn = rowGenerator()
a = []
while numRows > 0:
a.append(next(listn))
numRows -= 1
return a
文章标题:leetcode 118 杨辉三角 python
文章链接:http://soscw.com/index.php/essay/87587.html