#119
Pascal's Triangle II
EasyArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can compute the row directly using the properties of binomial coefficients, which allows us to build the row in a single pass without needing to store all previous rows.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a list with size rowIndex + 1, filled with 0.
- 2Step 2: Set the first element to 1, as the first element of any row in Pascal's Triangle is always 1.
- 3Step 3: For each index from 1 to rowIndex, calculate the value using the formula: row[j] = row[j - 1] * (rowIndex - j + 1) / j.
- 4Step 4: Return the constructed row.
solution.py6 lines
1def getRow(rowIndex):
2 row = [0] * (rowIndex + 1)
3 row[0] = 1
4 for j in range(1, rowIndex + 1):
5 row[j] = row[j - 1] * (rowIndex - j + 1) // j
6 return rowℹ
Complexity note: The time complexity is O(n) because we compute each element of the row in constant time. The space complexity is O(n) as we store the entire row.
- 1Each element in a row is the sum of the two elements directly above it.
- 2The nth row can be computed directly using binomial coefficients.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.