zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第119题:给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

    题目:
    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
    思路:
    思路简单,稍后看看题目的进阶做法,然后做相应的增加。
    程序1:(空间复杂度为O(k^2))
    class Solution:
        def getRow(self, rowIndex: int) -> List[int]:
            result = []
            if rowIndex <= 0:
                return [1]
            for index1 in range(1, rowIndex + 2):
                data = []
                if index1 == 1:
                    data.append(1)
                elif index1 == 2:
                    data.append(1)
                    data.append(1)
                else:
                    for index2 in range(0, index1):
                        if index2 == 0:
                            data.append(1)
                        elif index2 > 0 and index2 < index1 - 1:
                            data.append(result[index1 - 2][index2 - 1] + result[index1 - 2][index2])
                        else:
                            data.append(1)
                result.append(data)
            row = result[rowIndex]
            return row
    程序2:
    所需的空间为O(k),则构建一个长度为k的数组,计算过程模拟杨辉三角形出现的过程。
    class Solution:
        def getRow(self, rowIndex: int) -> List[int]:
            result = [1]*(rowIndex+1)
            for index1 in range(rowIndex+1):
                for index2 in range(index1 - 1, 0, -1):
                    result[index2] = result[index2 - 1] + result[index2]
            return result

     太难了,还是这么低。。。

  • 相关阅读:
    C#
    Excel 中大量图片如何快速导出? 转载自:http://www.zhihu.com/question/20800948
    IE的F12开发人员工具不显示 转载自:http://blog.csdn.net/longyulu/article/details/8749705
    firefox ie 比较 relative path
    fiddler save files
    selenium3加载浏览器
    Linux安装PHP
    客户端级别的渲染分析工具 dynaTrace
    前端性能分析:分析百度和sogou
    Linux vi的基本操作
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12746542.html
Copyright © 2011-2022 走看看