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]]
"""
rows = []
for i in range(numRows):
rows += [1],
if i == 0:
continue
else:
rows[-1] += [ rows[-2][x] + rows[-2][x - 1] for x in range(1, i)]
rows[-1] += 1,
return rows
Trick:
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] # the same as if not numsRows: return []
Explanation: Any row can be constructed using the offset sum of the previous row. Example:
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1