zoukankan      html  css  js  c++  java
  • leetcode118 Pascal's Triangle

     1 """
     2 Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
     3 In Pascal's triangle, each number is the sum of the two numbers directly above it.
     4 Example:
     5 Input: 5
     6 Output:
     7 [
     8      [1],
     9     [1,1],
    10    [1,2,1],
    11   [1,3,3,1],
    12  [1,4,6,4,1]
    13 ]
    14 """
    15 """
    16 解法一:
    17 先来一个自己写的AC
    18 直来直去,将第一行第二行单独拿出来讨论
    19 第三行以后按照规律循环
    20 """
    21 class Solution1:
    22     def generate(self, numRows):
    23         if numRows <= 0:
    24             return []
    25         if numRows == 1:
    26             return [[1]]
    27         res = [[1], [1, 1]]
    28         if numRows == 2:
    29             return res
    30         queue = [1, 1]
    31         while numRows - 2:
    32             temp = [1]
    33             for i in range(len(queue)-1):
    34                 temp.append(queue[i] + queue[i+1])
    35             temp.append(1)
    36             res.append(temp)
    37             queue = temp
    38             numRows -= 1
    39         return res
    40 """
    41 解法二:用map函数(自己知道这个函数,但想不到可以用,这就是和大佬的差距)
    42 新的一行前后各添0,再相加即为下一行
    43   0 1 3 3 1
    44  +1 3 3 1 0
    45  =1 4 6 4 1
    46 """
    47 class Solution:
    48     def generate(self, numRows: int) -> List[List[int]]:
    49         if numRows == 0:
    50             return []
    51         res = [[1]]
    52         for i in range(1, numRows):
    53             res.append(list(map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])))
    54             # map(function, list1, list2)
    55             #res[-1]代表当前最后一行,前后添0
    56             #  0 1 3 3 1
    57             # +1 3 3 1 0
    58             # =1 4 6 4 1
    59         return res
    60         # '+'与extend功能相同,合二为一 []+[]=[]
    61         # append是再末尾添加新的对象 [].append([]) = [[]]
  • 相关阅读:
    用户管理
    开机、重启、用户登录注销
    网络请求的封装
    Vuex
    Promise
    Vue Router(二)
    Vue Router(一)
    Vue CLI
    前端模块化-导入导出
    插槽
  • 原文地址:https://www.cnblogs.com/yawenw/p/12375446.html
Copyright © 2011-2022 走看看