118. Pascal's Triangle

来源:互联网 发布:手机必备实用软件 编辑:程序博客网 时间:2024/06/02 03:24

题意: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]]

思路:这个是开始学c++的时候遇到过的第一题吧,先放一个正常的代码:

class Solution(object):    def generate(self, numRows):        """        :type numRows: int        :rtype: List[List[int]]        """        ans = [[0]*i for i in xrange(1, numRows+1)]        for i in xrange(numRows):            ans[i][0] = ans[i][-1] = 1            for j in xrange(1, i):                ans[i][j] = ans[i-1][j-1] + ans[i-1][j]        return ans

下面这个就有点新意了,它巧妙的运用了map函数和1,4,6,3,1 = 0,1,3,3,1 + 1,3,3,1,0,下一行等于上一行首位补零后求和:

class Solution(object):    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]
0 0
原创粉丝点击