118. 杨辉三角

https://leetcode-cn.com/problems/pascals-triangle/

解法一:迭代

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res = [[1], [1,1]]
        if numRows < 3:     #前两层特殊
            return res[:numRows]
        row = [1,1]
        #从第三层开始,一层层迭代
        for i in range(3, numRows+1):
            new_row = [1] * i   #新层初始全1
            for j in range(1, i-1):
                new_row[j] = row[j-1] + row[j]
            row = new_row   #替换旧层
            res.append(new_row)
        return res

最后更新于