Leetcode118-Pascal's Triangle

2017-09-20  本文已影响0人  LdpcII

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
上一篇下一篇

猜你喜欢

热点阅读