题目
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
1
1 1
1 2 1
1 3 3 1
......
题解
空间使用率 o(2 * rowIndex)
杨辉三角下一列会用到前一列的状态,使用pre保存上次状态,即可推导出rowIndex行情况。
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex < 2:
return [1, 1] if rowIndex else [1]
pre, res = [1, 1], []
for i in range(2, rowIndex+1):
res = [1 for _ in range(i+1)]
for j in range(1, i):
res[j] = pre[j-1] + pre[j]
pre = res
return res
空间使用率 o(rowIndex)
在上一种实现方式的基础上,将保存状态的列表并归到结果列表。
由杨辉三角特性可知:
1. 第row行第col个元素,是由上一行的第col以及col-1个元素之和,且只与之相关;
2. 第row行有row+1个元素。
动态规划解题:
1. 初始化: dp = [1 for _ in range(rowIndex+1)];
2. 遍历方式:由于 rows[row][col] = rows[row-1][col] + rows[row-1][col-1],
当维度将为1时,要保持col-1、col状态,故而需要从后往前遍历;
由于需要获取前一状态情况,需要在已知前两行情况下往后推导;
故而遍历公式:
for row in range(2, rowIndex+1):
for col in range(row-1, 0, -1):
res[col] = res[col] + res[col-1]
3. 推导公式:rows[col] = rows[col] + rows[col-1]
代码实现
class Solution:
def getRow(self, rowIndex: int) -> list:
if rowIndex <= 1:
return [1, 1] if rowIndex else [1]
res = [1 for _ in range(rowIndex + 1)]
for row in range(2, rowIndex + 1):
for col in range(row - 1, 0, -1):
res[col] = res[col] + res[col - 1]
return res
该文介绍了如何使用动态规划优化杨辉三角的Python实现,通过减少空间使用率,从O(2*rowIndex)降低到O(rowIndex),主要涉及列表操作和遍历策略。
381

被折叠的 条评论
为什么被折叠?



