题目:杨辉三角 II
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。如下图。
提醒:如果输入为0,输出 [1]。
----------------------------------------------------------------------
解法1:Pascal三角形的原理就是简单的累加,可以通过python自带的map() 映射来实现。
map() 会根据提供的函数对指定序列做映射。map(function, iterable, ...)
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0:
return [1]
pas = [1]
for i in range(rowIndex):
# 解析,例如第二行: ([0]+[1]) + ([1]+[0]) = [1,1]
newLine = list(map(lambda x,y:x+y, [0]+pas, pas+[0]))
pas = newLine
return pas
解法2:看看网友的高招,不用map()函数,效率得到进一步提升。
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0:
return [1]
pas = [1]
for j in range(rowIndex):
pas = [1] + [pas[i]+pas[i+1] for i in range(len(pas)-1)] +[1]
return pas
参考:
https://www.runoob.com/python/python-func-map.html
https://blog.csdn.net/qq_34364995/article/details/80518162
https://blog.csdn.net/qq_38575545/article/details/85803923