Given an integer rowIndex
, return the rowIndex
th (0-indexed) row of the Pascal’s Triangle.
In Pascal’s Triangle, each number is the sum of the two numbers directly above it as shown:
Example:
Input: rowIndex = 3
Output: [1, 3, 3, 1]
Constraints:
- 0 <= rowIndex <= 33
rowIndex
guaranteed to fall within the specified constraints?
rowIndex
is guaranteed to be between 0 and 33.To generate the rowIndex
th row of Pascal’s Triangle, we can utilize the following properties:
Here’s a step-by-step plan:
[1]
.rowIndex
. For each row, generate new elements by summing appropriate elements from the previous row, with the rule that the first and the last elements are always 1.def getRow(rowIndex):
row = [1]
for _ in range(rowIndex):
row = [x + y for x, y in zip([0] + row, row + [0])]
return row
# Example usage:
print(getRow(3)) # Output: [1, 3, 3, 1]
O(rowIndex^2)
. This is because each row generation involves summing operations, which takes linear time concerning the number of elements in the row. Summing up these operations for all rows leads to an overall quadratic time complexity.O(rowIndex)
. We use a single list to store the current row, which grows up to rowIndex + 1
in size.This approach efficiently generates the desired row while keeping space usage minimal.
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?