给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: rowIndex = 3 输出: [1,3,3,1]
示例 2:
输入: rowIndex = 0 输出: [1]
自身解题思路:
在上一题(118.杨辉三角Ⅰ)的解题过程的基础上稍作添加即可,要得到第rowindex行,我们先生成rowindex+1行的杨辉三角元素(因为rowindex是从第0行开始的) ,最后返回生成的杨辉三角最后一行即可
代码实现:
def getRow(rowIndex):
result = generate(rowIndex+1)
return result[-1]
def generate(num):
if num == 0:
return []
res = [[1]]
while len(res) < num:
newRow = [a + b for a, b in zip([0] + res[-1], res[-1] + [0])]
res.append(newRow)
return res
print(getRow(3))
输出:
缺点:因为需要枚举杨辉三角的每一行,再返回最后一行,空间复杂度比较高
解题思路二:
优化空间复杂度为
我们只用一个长度为 kk 的一维数组。类似于动态规划中滚动数组的思路。
使用一维数组,然后从右向左遍历每个位置,每个位置的元素
为啥不从左向右遍历呢?因为如果从左向右遍历,那么左边的元素已经更新为第 i 行的元素了,而右边的元素需要的是第 i - 1i−1 行的元素。故从左向右遍历会破坏元素的状态。
代码实现:
def getRow(rowIndex):
res = [1] * (rowIndex + 1)
for i in range(2, rowIndex + 1):
for j in range(i - 1, 0, -1):
res[j] += res[j - 1]
return res
print(getRow(4))
输出:
不太容易理解,可作为一种了解
解题思路三:
还是观察到,当前行元素等于上一行元素与其错位相加,在上一行首位添加0再求和即可得到当前行元素的值
def getRow(rowIndex):
res = [1]
for i in range(rowIndex):
res = [a + b for a, b in zip([0] + res, res + [0])]
return res
print(getRow(3))
输出: