LeetCode Pascal's Triangle

LeetCode解题之Pascal’s Triangle


原题

要求得到一个n行的杨辉三角。

注意点:

样例:

输入: numRows = 5

输出:

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

解题思路

杨辉三角的特点是每一行的第一和最后一个元素是1,其他元素是上一行它左右两个元素之和。

以[1,3,3,1]为例,下一行的中间元素就是[1+3,3+3,3+1],也就是[1,3,3]和[3,3,1]相应数字求和。

AC源代码

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if not numRows:
            return []
        result = [[1]]
        while numRows > 1:
            result.append([1] + [a + b for a, b in zip(result[-1][:-1], result[-1][1:])] + [1])
            numRows -= 1
        return result


if __name__ == "__main__":
    assert Solution().generate(4) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

posted @ 2018-04-07 19:21  llguanli  阅读(96)  评论(0编辑  收藏  举报