118. 杨辉三角

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

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

 1 class Solution(object):
 2     def generate(self, numRows):
 3         """
 4         :type numRows: int
 5         :rtype: List[List[int]]
 6         """
 7         a = []
 8         if numRows == 0:
 9             return a
10         # 初始化
11         for i in range(1, numRows + 1):
12             a.append([0] * i)
13         print(a)
14         # 最顶端元素
15         a[0][0] = 1
16         for i in range(1, numRows):
17             for j in range(i + 1):
18                 # 每一行第一个和最后一个元素都是1
19                 if j == i or j == 0:
20                     a[i][j] = 1
21                 # 否则是肩上两个元素之和
22                 else:
23                     a[i][j] = a[i - 1][j] + a[i - 1][j - 1]
24         return a
25 
26 
27 if __name__ == '__main__':
28     solution = Solution()
29     print(solution.generate(5))
原文地址:https://www.cnblogs.com/panweiwei/p/12748728.html