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: # @return a list of lists of integers def generate(self, numRows): def g(ls): res = [1] left = 1 for i in range(1,len(ls)): res.append(left+ls[i]) left = ls[i] res.append(1) return res res = [] if numRows < 3: if numRows == 0: return res for i in range(1,numRows+1): res.append([1]*i) else: res.append([1]) res.append([1,1]) for i in range(2,numRows): res.append(g(res[i-1])) return res
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: # @return a list of integers def getRow(self, rowIndex): def g(ls): res = [1] left = 1 for i in range(1,len(ls)): res.append(left+ls[i]) left = ls[i] res.append(1) return res res = [] if rowIndex< 2: res = [1]*(rowIndex+1) else: res.append([1,1]) for i in range(rowIndex): res = (g(res)) return res