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% 的用户
posted on 2019-05-11 16:11 imyourterminal 阅读(141) 评论(0) 编辑 收藏 举报