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% 的用户
  • 相关阅读:
    《梦断代码》读后感(二)
    《梦断代码》读后感(一)
    最大子数组和(环状数组)
    求最大字数组的和的1000个元素的新要求
    面试题fugui02
    Linux基本操作
    面试题fugui
    水星的水
    python魔术方法
    tornado websocket聊天室
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10848986.html
Copyright © 2011-2022 走看看