118. Pascal's Triangle

题目来源:https://leetcode.com/problems/pascals-triangle/
 自我感觉难度/真实难度:             写题时间时长:

 题意:写一个金字塔类型

 分析:
 自己的代码:
class Solution(object):
    def generate(self, n):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if n==0:
            return []
        if n==1:
            return [[1]]
        res=[[1],[1,1]]
        for i in range(3,n+1):
            templ=[]
            if i%2==0:
                end=i/2
                while end-1:
                    templ.append(res[i-1-1][-1*end]+res[i-1-1][1-end])
                templ.append(1)
                templ.reverse()
                templ.extend(templ[::-1])
                
                
            else:
                end=(i//2)+1
                while end-1:
                    templ.append(res[i-1-1][-1*end]+res[i-1-1][1-end])
                templ.append(1)
                templ.reverse()
                templ.extend(templ[:-end+1:])
            res.append(templ)
            return res

TLM

代码效率/结果:

 优秀代码:

def generate(self, numRows):
        res = [[1]]
        for i in range(1, numRows):
            res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
        return res[:numRows]

class Solution(object):
    def generate(self, numRows):
        a=[]
        for i in range(numRows):
            a.append([1]*(i+1))
            if i>1:
                for j in range(1,i):
                    a[i][j]=a[i-1][j-1]+ a[i-1][j]
        return a

 

代码效率/结果:
 自己优化后的代码:

 反思改进策略:

1.数学规律不一定是最快的,数学计算技巧有时很重要

2.如何给list赋值全为一定个数的1,使用[1]*n

转载于:https://www.cnblogs.com/captain-dl/p/10854240.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值