1. 程式人生 > >leetcode 118 楊輝三角 python

leetcode 118 楊輝三角 python

span self [1] lse list tor pytho while sel

楊輝三角  一開始自己使用的方法
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