题目来源:
https://leetcode.com/problems/pascals-triangle-ii/description/
题目分析:
本题与118题非常类似,但是需要注意区别。118题给定的是层数,而本题是索引i。第一层对应的索引i=0,由此可见,当i=3时,对应的是第4层的列表。我们可以先把整体的列表求出来后,取最后一个列表得到结果。
实现代码:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
biao = []
for i in range(rowIndex+1):
biao.append([1] * (i + 1))
if (i > 1):
for j in range(1, i):
biao[i][j] = biao[i - 1][j - 1] + biao[i - 1][j]
return biao[-1]
先前的python2所实现的偏移相加的方法,在这里改进后可以用python3实现。其具体代码为:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [[1]]
for i in range(0, rowIndex):
res.append(list(map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])))
return res[-1]