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] ]
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ res = [[1]] for i in range(1,numRows): res += [map(lambda x, y:x+y,res[-1]+[0],[0]+res[-1])] return res[:numRows] # [[1]]+[0] -> [[1],0] # [[1]]+[0,1] ->[[1],0,1] # [[1]]+[[0]] -> [[1],[0]] # [[1]]+0 -> error # the code is elegant, but slow. the reason lies in the fact that it generates too much list while looping # be careful when numRows is 0, res[:numRows] will return [] when it happens
119. Pascal‘s Triangle II
Given an index k, return the kth row of the Pascal‘s triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ res = [1] for i in range(0, rowIndex): res = [ i+j for i,j in zip(res + [0], [0] + res)] return res # list can‘t be added elementwisely with +