Leetcode: Pascal’s Triangle
1 min readDec 25, 2016
This is a fairly simple problem. To create the next row we need to use the values present in the previous row.
- Initialize the result with the first row
- To create a new row, find the last row in the result
- Pair-wise add the element in this row to get the middle element of the new row
- Add 1 to each end of the new row
- Append it to result
Remarks:
- For generating n rows we need to generate O(n²) elements, hence both the time and space complexity are O(n²)
Extension:
- Print the nth row of the Pascal’s triangle
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
res = [[1]]
for j in range(numRows - 1):
prev = res[-1]
next = [1]
for i in range(len(prev) - 1):
next.append(prev[i] + prev[i + 1])
next.append(1)
res.append(next) return res