首页 > 其他 > 详细

118. Pascal's Triangle

时间:2019-05-13 00:08:20      阅读:139      评论:0      收藏:0      [点我收藏+]

题目来源: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

118. Pascal's Triangle

原文:https://www.cnblogs.com/captain-dl/p/10854240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!