当前位置: 代码迷 >> 综合 >> Leetcode 119. 杨辉三角 II(Python3)
  详细解决方案

Leetcode 119. 杨辉三角 II(Python3)

热度:78   发布时间:2023-12-23 10:24:35.0

119. 杨辉三角 II

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 3
输出: [1,3,3,1]

进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

 

代码:

class Solution:def getRow(self, rowIndex):""":type rowIndex: int:rtype: List[int]"""res = []for i in range(rowIndex+1):cr = [1]*(rowIndex+1)         if i > 1:for j in range(1,i):cr[j] = res[j-1] + res[j]res = crreturn res

 

大佬的两种写法:

class Solution:def getRow(self, rowIndex):""":type rowIndex: int:rtype: List[int]"""# method one# row = [1]# for i in range(1,rowIndex+1):#     row = list(map( lambda x,y : x+y , row + [0] , [0] + row )) # return row        # method two    老土的方法,但有效,不用借助高等函数map()res = [1]for i in range(1, rowIndex+1):res = [1] + [res[i] + res[i + 1] for i in range(len(res) - 1)] + [1]return res