• 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

  • 相关阅读:
    sql时间天数操作
    SQL死锁
    sql操作数据库结构
    sql设置时间显示格式
    sql树形结果,查询所有子类
    centos6.5 mysql 安装
    windows git 使用
    centos6.5 vsftpd的搭建
    centos 6.5 Nginx安装
    jQuery源码中的Ajax--load方法
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10854240.html
Copyright © 2020-2023  润新知