【LeetCode每天一题】Pascal's Triangle(杨辉三角)

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 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), 然后在遍历求中间每一个位置的具体数。时间复杂度为O(n2), 空间复杂度为O(n2) (第一行一个, 第二行两个, 第三行三个, 以此类推累加公式 然后去除系数)

解决代码:
 1 class Solution(object):
 2     def generate(self, numRows):
 3         """
 4         :type numRows: int
 5         :rtype: List[List[int]]
 6         """   
 7         res = [[1]*(i+1) for i in range(numRows)]  # 根据输入创建相应数据
 8         
 9         for i in range(2, numRows): # 从第三行开始,前两行不需要计算。
10             for j in range(1,i):      
11                 res[i][j] = res[i-1][j-1] + res[i-1][j]
12         return res



  
原文地址:https://www.cnblogs.com/GoodRnne/p/10584388.html