给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。在杨辉三角中,每个数是它左上方和右上方的数的和。
-
示例:
输入: 3
输出: [1,3,3,1] -
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
答案和118题杨辉三角一样,只是取一下最后一项即可。(未考虑进阶要求)
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
result = [[1]]
while len(result) < rowIndex + 1:
result.append([a + b for a, b in zip(result[-1] + [0], [0] + result[-1])])
return result[-1]