zoukankan      html  css  js  c++  java
  • 119. Pascal's Triangle II

    Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

    Note that the row index starts from 0.

    Follow up:

    Could you optimize your algorithm to use only O(k) extra space?

    用递归写的,我记得说过要用递归做的吧,结果超时了我去

    class Solution:
        def getRow(self, rowIndex):
            row = rowIndex
            col = 0
            a = []
            for i in range(row+1):
                b = self.getElement(row, col)
                a.append(b)
                col = col + 1
            return a
    
        def getElement(self, row, col):
            if ((col == 0) | (row == col)):
                return 1
            else:
                return self.getElement(row - 1, col - 1) + self.getElement(row - 1, col)

    获取杨辉三角的指定行 直接使用组合公式C(n,i) = n!/(i!*(n-i)!) 则第(i+1)项是第i项的倍数=(n-i)/(i+1);

    class Solution:
        def getRow(self, rowIndex):
            a=[]
            b=1
            for i in range(rowIndex+1):
                a.append(int(b));
                b=b*(rowIndex-i)/(i+1)
            return a
    执行用时 : 52 ms, 在Pascal's Triangle II的Python3提交中击败了83.87% 的用户
    内存消耗 : 13 MB, 在Pascal's Triangle II的Python3提交中击败了88.89% 的用户
  • 相关阅读:
    vim编辑器
    linux常用的命令解释
    克隆虚拟机及本地仓库的搭建
    创建windows系统下的虚拟机
    创建linux系统下的虚拟机
    drf频率组件
    django中过滤 搜索 排序
    drf分页
    js回顾
    数据类型
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10848986.html
Copyright © 2011-2022 走看看