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]
]
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
triangle=[]
row=[]
for rowid in range(numRows):
row[0]=1 <=====out of range
if rowid > 1:
row[0],row[-1]=1,1
for i in range(1, len(row)-1):
row[i]=triangle[[rowid-1][i-1]]+triangle[[rowid-1][i]]
triangle.append(row)
return triangle
调整如下:
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
triangle=[]
for rowid in range(numRows):
row=[None for _ in range(rowid+1)]
row[0],row[-1]=1,1
for i in range(1,len(row)-1):
row[i]=triangle[rowid-1][i-1]+triangle[rowid-1][i]
triangle.append(row)
return triangle
Note:
range()函数和for-in循环
函数原型:range(start, end, scan):
参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
end:技术到end结束,但不包括end 。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)