LeetCode-118. 杨辉三角

118. 杨辉三角


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

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

示例:

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

解题思路:这道题很简单,只需要按照题意描述使用上一层的数字计算本层数字即可。

Python3代码如下:

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if not numRows:
            return []
        if numRows == 1:
            return [[1]]
        if numRows == 2:
            return [[1],[1,1]]
        result = [[1],[1,1]]
        for i in range(numRows-2):
            temp = [1]
            for j in range(i+1):
                temp.append(result[-1][j]+result[-1][j+1])
            temp.append(1)
            result.append(temp)
        return result

猜你喜欢

转载自blog.csdn.net/qq_36309480/article/details/89682277
今日推荐