zoukankan      html  css  js  c++  java
  • 159-118. 杨辉三角

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行(第一个我写的,我越优化,效率越低,懵逼)
    class Solution(object):
        def generate1(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """
            temp_list = [1 for _ in range(numRows)]
            ret_list = []
    
            for i in range(0, numRows):
                if i < 2:
                    ret_list.append(temp_list[:i+1])
                    continue
                pre_value = 1
                for j in range(1, i):
                    cur_value = temp_list[j]
                    temp_value = pre_value + cur_value
                    pre_value = cur_value
                    temp_list[j] = temp_value
    
                ret_list.append(temp_list[:i+1])
            return ret_list
    
        def generate2(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """
            angleArr = []
            for index in range(0, numRows):
                arr = []
                for j in range(index + 1):
                    if j == 0 or j == index:
                        arr.append(1)
                    else:
                        newItem = angleArr[index - 1][j - 1] + angleArr[index - 1][j]
                        arr.append(newItem)
                angleArr.append(arr)
            return angleArr
    
        def generate(self, numRows):
                """
                :type numRows: int
                :rtype: List[List[int]]
                """
                result = []
                for i in range(numRows):
                    now = [1]*(i+1)
                    if i >= 2:
                        for n in range(1,i):
                            now[n] = pre[n-1]+pre[n]
                    result += [now]
                    pre = now
                return result
    
    
    if __name__ == '__main__':
        s1 = Solution()
        n = 7
        root = s1.generate(n)
        print(root)
    
  • 相关阅读:
    【转】awk内置变量
    【转】awk数组操作
    【转】awk 数组用法【精华贴】
    【转】linux shell 逻辑运算符、逻辑表达式
    指挥作战
    人脸相关
    TD
    后台
    前台 html 空格
    linux
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14335736.html
Copyright © 2011-2022 走看看