题目
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
我的起始解法:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = [1] * (rowIndex + 1)
temp = [1] * (rowIndex + 1)
for n in range(2, rowIndex + 1):
for i in range(0, n - 1):
result[i + 1] = temp[i] + temp[i + 1]
for i in range(1, n):
temp[i] = result[i]
return result
因为在从前往后更新result列表时,会产生副作用(相加后会改变前面的值,导致下一次相加的信息不对),所以用了个临时列表temp保存原始的值。
改进后的代码:
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = [1] * (rowIndex + 1)
for n in range(2, rowIndex + 1):
for i in range(n - 1, 0, -1):
result[i] += result[i - 1]
return result
从后往前加就没有了副作用的影响
总结:思考问题的时候要从多个方向分析,不要死脑经只想到从前往后
不过改进后的代码提交后速度反而到了10%不到,之前的代码超过了96%,感觉是leetcode的bug