LeetCode Pascal's Triangle

来源:互联网 发布:mac book可以安装vs么 编辑:程序博客网 时间:2024/06/05 19:25

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 resultif __name__ == "__main__":    assert Solution().generate(4) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

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

0 0