Pascal's Triangle II Problem
Description
LeetCode Problem 119.
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.
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Constraints:
- 0 <= rowIndex <= 33
Solution
Approach: One Row, Updated In Place
Each entry of a row is the sum of the two entries above it: row[r][j] = row[r-1][j-1] + row[r-1][j]. We only ever need the previous row, so we can keep a single array of length rowIndex + 1 and turn it into the next row again and again.
- Fill the array with 1s. The first and last entry of every row is 1, so those never need computing.
- For each row
rfrom 2 torowIndex, update the inner entriesj = r - 1down to1withrow[j] += row[j - 1].
The direction matters. If we went left to right, row[j - 1] would already hold the new value of row r when we compute row[j], and the sums would be wrong. Going right to left, row[j - 1] is still the value from row r - 1.
For rowIndex = 3: [1,1,1,1] → row 2 gives [1,2,1,1] → row 3 gives [1,3,3,1].
Complexity: O(k2) time and O(k) space, where k is rowIndex.
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
row = [1] * (rowIndex + 1) # the first and last entry of every row is 1
for r in range(2, rowIndex + 1):
# Turn row r - 1 into row r in place. Go right to left so row[j - 1] is still the old value.
for j in range(r - 1, 0, -1):
row[j] += row[j - 1]
return row