zoukankan      html  css  js  c++  java
  • LeetCode--119--杨辉三角II

    问题描述:

    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:

    输入: 3
    输出: [1,3,3,1]
    

    进阶:

    你可以优化你的算法到 O(k) 空间复杂度吗?

    方法1:

     1 class Solution(object):
     2     def getRow(self, rowIndex):
     3         """
     4         :type rowIndex: int
     5         :rtype: List[int]
     6         """
     7         if rowIndex == 0:
     8             return [1]
     9         s = [[1]]
    10         for i in range(1,rowIndex + 1):
    11             t = []
    12             for j in range(i+1):
    13                 if j == 0 or j == i:
    14                     t.append(1)
    15                 else:
    16                     t.append(s[-1][j] + s[-1][j-1])
    17             s.append(t)
    18         return s[-1]

    官方:(未理解)

     1     def getRow(self, rowIndex):
     2         """
     3         :type rowIndex: int
     4         :rtype: List[int]
     5         """
     6         l = [1]
     7        
     8         for t in range(rowIndex):
     9             l = [sum(i) for i in zip(l+[0], [0]+l)]
    10            
    11         return l

    规律:***

     1 class Solution(object):
     2     def getRow(self, rowIndex):
     3         """
     4         :type rowIndex: int
     5         :rtype: List[int]
     6         """
     7         res = [1]
     8         for i in range(rowIndex):
     9             res.append(res[-1] * (rowIndex-i) / (i+1))
    10         return res

    2018-09-11 20:04:00

  • 相关阅读:
    MySQL decimal unsigned 更新负数不报错却为0
    centos 安装jdk
    CentOS7安装docker
    Cron 时间元素
    PHPStorm
    日志习惯
    HTTP幂等性
    navicat for mysql 10.1.7注册码
    localStorage、sessionStorages 使用
    FreePascal
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9629927.html
Copyright © 2011-2022 走看看