美文网首页
Leetcode118-Pascal's Triangle

Leetcode118-Pascal's Triangle

作者: LdpcII | 来源:发表于2017-09-20 16:03 被阅读0次

    118. Pascal's Triangle

    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]
    ]

    My Solution

    class Solution(object):
        def generate(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """
            if numRows == 0:
                return []
            if numRows == 1:
                return [[1]]
            if numRows == 2:
                return [[1], [1, 1]]
            result, sub = [[1], [1, 1]], [1]
            for i in range(2, numRows):
                for j in range(1, i):
                    sub.append(result[i-1][j-1] + result[i-1][j])
                sub.append(1)
                result.append(sub)
                sub = [1]
            return result
    

    Reference (转)

    def generate(self, numRows):
            res = [[1]]
            for i in range(1, numRows):
                res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
            return res[:numRows]
    
    Example:
           1 3 3 1 0 
        +  0 1 3 3 1
        =  1 4 6 4 1

    相关文章

      网友评论

          本文标题:Leetcode118-Pascal's Triangle

          本文链接:https://www.haomeiwen.com/subject/nveosxtx.html