leetcode-118 python 杨辉三角

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

《leetcode-118 python 杨辉三角》
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解题要点:

1.观察最后一层与倒数第二层数列之间的关系,利用递归即可求出;

class Solution:
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        ans = []
        ss = []
        if numRows == 0:
            return []
        if numRows == 1:
            return [[1]]
        if numRows == 2:
            return [[1],[1,1]]
        temp = self.generate(numRows-1)
        kk = temp[numRows-2]
        for i in range(numRows):
            if i == 0 or i == numRows-1:
                ss += [1]
            else:
                ss.insert(i, kk[i-1]+kk[i])
        ans = temp + [ss]
        return ans

后来借鉴改进后发现使用递推而不是递归的方法会更好一点,更好理解也更好使用内存;

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/chkay399/article/details/80933079
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞