首页 > 其他 > 详细

119. Pascal's Triangle II

时间:2019-05-11 16:29:59      阅读:142      评论:0      收藏:0      [点我收藏+]

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% 的用户

119. Pascal's Triangle II

原文:https://www.cnblogs.com/dmndxld/p/10848986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!