Given an integer numRows
, return the first numRows
of Pascal’s triangle. In Pascal’s triangle, each number is the sum of the two numbers directly above it.
numRows
?
1 <= numRows <= 30
based on common test cases.numRows
is 0?
[]
.The problem requires generating Pascal’s triangle up to a given number of rows. Each row in Pascal’s triangle starts and ends with the number 1, and each interior number is the sum of the two numbers above it from the previous row.
Steps to achieve this:
[1]
.numRows
:
[1]
.[1]
.def generate(numRows):
if numRows == 0:
return []
triangle = []
for row_num in range(numRows):
# Start with a row of `1`s
row = [1] * (row_num + 1)
# Calculate the interior values
for j in range(1, row_num):
row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]
triangle.append(row)
return triangle
# Example usage
print(generate(5))
The time complexity of this approach is (O(n^2)), where n
is numRows
. This is because:
n
iterations).k
iterations, where (k \leq n)).Thus, the overall complexity is driven by the nested loops iterating through all the elements of the triangle.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?