Given an integer numRows, return the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
图示:
https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
#初始化第0行第0列也就是最尖上的是[1]
rows = [[1]]
#for循环能够占位子,每一行的位子固定有几个,用[1]占位
for r in range(1, numRows):
rows.append([1] * (r+1))
#从后往前计算
for c in range(1, r):
rows[r][c] = rows[r-1][c] + rows[r-1][c-1]
return rows