[Leetcode]Pascal's Triangle

来源:互联网 发布:太原知达常青藤初中 编辑:程序博客网 时间:2024/05/16 00:25

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return

[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]


给定行数n,让你返回Pascal's triangle的前n行~ 每一行的元素(除了第一个和最后一个)都是上一行两个相邻元素相加的结果~ 时间复杂度为O(n^2)

(虽然能一次写对,但感觉写的比较慢,效率还有待提升)

class Solution:    # @return a list of lists of integers    def generate(self, numRows):        if numRows <= 0: return []        res = [[1]]        for i in xrange(1, numRows):            tmp = [1]            j = 1            while j < i:                tmp.append(res[i - 1][j - 1] + res[i - 1][j])                j += 1            tmp.append(1)            res.append(tmp)        return res


0 0
原创粉丝点击