Leetcode 118题 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.
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题目大意: 给一个数n,构造n层的杨辉三角。杨辉三角如图所示。
思路是先用1构造这个三角形,然后再一行一行遍历修改其中的值。
直接上代码。
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(0,numRows):
res.append([1]*(i+1)) #构造三角形
for j in range(1,i): #再遍历,修改每个值。
res[i][j] = res[i-1][j-1] + res[i-1][j]
return res
疫情中的英国,
加油!
04/05/2020