杨辉三角 一开始自己使用的方法 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
原文地址:https://www.cnblogs.com/feyfree/p/9743186.html
时间: 2024-10-09 16:40:23