LeetCode118 119 杨辉三角(Python)

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

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

示例:

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

代码实现:

class Solution(object):
    def yhTriangle(self,rowcount):
        res = [[1]]

        for i in range(1, rowcount):
            #利用匿名函数lambda以及map函数进行优化,关于两种函数的使用请自行百度
            res.append(list(map(lambda x, y : x + y, [0] + res[-1], res[-1] + [0])))
        #输出前rowcount行
        #return res
        #输出第rowcount行
        return res[rowcount-1:]

猜你喜欢

转载自blog.csdn.net/Manson_Wang/article/details/81983004