(Leetcode) 杨辉三角形ii - Python实现

题目:杨辉三角 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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值