118. 杨辉三角

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

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

  • 示例:

输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

  • 分析:

根据图示规律,第一步应生成以1开始,以1结束的 n 行列表,从第2行开始, 该列表中间的值由上一行开始值+结束值得到

  • 解法:

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
		res = []
        for line in range(num_rows):
            tmp = [1]*(line+1)
            res.append(tmp)
            for row in range(1, line):
                res[line][row] = res[line-1][row-1] + res[line-1][row]
        return res

posted @ 2019-05-04 16:28  AimeeGao  阅读(136)  评论(0编辑  收藏  举报