题目
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]
]
思路
这道题虽然output呈现的是三角形,但其实不用考虑空格的问题
先观察图形,可以发现的规律是第一行1个数,第二行2个数…第n行n个数,每一行的第一个和最后一个数是1,其余的是上一行的列索引-1+列索引之和
用python的list来求解
代码
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
r=[]
for i in range(numRows):
#生成空的二维数组
r.append([])
for j in range(i+1):
#第n行就有n个数,i+1因为range不包含最后一个数
if j in (0,i):
#第一个和最后一个是1
r[i].append(1)
else:
r[i].append(r[i-1][j-1]+r[i-1][j])
return r
顺便附上119的代码,弄清楚边界问题就好
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
r=[]
for i in range(rowIndex+1):
r.append([])
for j in range(i+1):
if j in(0,i):
r[i].append(1)
else:
r[i].append(r[i-1][j-1]+r[i-1][j])
return r[rowIndex]
总结
这道题思路不难,用循环嵌套可以解决,但就是需要对python的数据结构较熟悉,比如生成空数组r.append([]),对每一行的一维数组添加值需要指定行数r[i].append()