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

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

  • 相关阅读:
    IE 11 使用 flexbox 垂直居中 bug
    Electron build 无法下载 winCodeSign 等资源
    Electron 开发环境下总是 crash
    解决 Electron 包下载太慢问题
    Netty--数据通信和心跳检测
    Netty编解码技术和UDP实现
    Netty入门
    Java 网络IO编程(BIO、NIO、AIO)
    java.util.concurrent常用类(CountDownLatch,Semaphore,CyclicBarrier,Future)
    JDK多任务执行框架(Executor框架)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12746542.html
Copyright © 2011-2022 走看看