改进前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res=[]
"""
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
"""
for i in range(numRows):
row=[1] # start with 1
if i>=1: # less than 1 then result append [1] and return
pre_row=res[i-1] # store the list of previous row
for j in range(i-1):
row.append(pre_row[j]+pre_row[j+1])
row.append(1) # end with 1
res.append(row)
return res

改进后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = []

for i in range(numRows):
row = [1] # start with 1

if i > 0:
prev_row = result[i-1]
num_elements = (i + 1) // 2 # 只计算一半的元素

for j in range(1, num_elements):
element = prev_row[j-1] + prev_row[j] # 通过对称性计算元素
row.append(element)

# 奇数个元素单独考虑:因为i从0开始,所以如果i为偶数,则每行有奇数个元素
if i % 2 == 0:
odd_row=row[:num_elements]
element = prev_row[num_elements - 1] + prev_row[num_elements]
row.append(element)

# 生成另一半
row += odd_row[::-1] if i % 2 == 0 else row[::-1]

result.append(row)

return result

Pascal’s Triangle II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
res = []
for i in range(rowIndex + 1): # Fix the loop range to include rowIndex
row = [1]
if i >= 1: # Change the condition to >= 1
pre_row = res[i - 1]
mid=(i+1)//2
for j in range(1,mid):
row.append(pre_row[j-1] + pre_row[j])
if i%2==0:
odd_row=row[:mid]
row.append(pre_row[mid-1]+pre_row[mid])
row+=odd_row[::-1] if i%2==0 else row[::-1]
res.append(row)
return res[-1]