118 Pascal ' s Triangle
Given numrows, generate the first numrows of Pascal ' s triangle.
For example, given numrows = 5,
Return
[ 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 L ist while looping # being careful when NumRows is 0, Res[:numrows] would 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 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 +
Leetcode with Python, Array