We need to build Pascal's triangle row by row. Each row starts and ends with 1, and every element in between is the sum of the two elements directly above it from the previous row.
Row 0 is [1]. Row 1 is [1, 1]. For row 2, the edges are 1, and the middle element is 1 + 1 = 2, giving [1, 2, 1]. Row 3 takes the middle values from row 2: 1 + 2 = 3 and 2 + 1 = 3, producing [1, 3, 3, 1].
Row i has exactly i + 1 elements, and element j in row i (where j is not the first or last) equals row[i-1][j-1] + row[i-1][j]. This dependency on the previous row is what drives the solution.
1 <= numRows <= 30 → With numRows at most 30, the total number of elements is at most 465. Even an O(n^3) approach would be trivially fast. There is no performance pressure here.Build Pascal's triangle the same way you'd draw it by hand. Start with the first row [1], then generate each subsequent row from the one before it.
For each new row, the first and last elements are always 1. Each interior element is the sum of the two values directly above it in the previous row. A single nested loop produces the whole triangle.
[[1]].i from 1 to numRows - 1:[1].j from 1 to i - 1, compute the value as previousRow[j-1] + previousRow[j] and append it.This approach is optimal in time, since the output alone contains O(n^2) elements. The next approach reaches the same complexity through a different route: it computes each row from a closed-form binomial formula, without referencing the previous row.
Every element in Pascal's triangle is a binomial coefficient. Specifically, element j in row i equals C(i, j) = i! / (j! * (i-j)!).
Computing factorials directly would be wasteful and risk overflow, since intermediate factorials grow far faster than the final coefficients. Instead, derive each element from the one before it in the same row using a ratio:
C(i, j) = C(i, j-1) * (i - j + 1) / j
Each row starts with 1 (since C(i, 0) = 1), and multiplying by this ratio produces the next element. The previous row never enters the computation.
The ratio identity follows from the factorial definition. C(n, k) = n! / (k! (n-k)!) and C(n, k-1) = n! / ((k-1)! (n-k+1)!). Dividing the first by the second cancels n! and most of the other factorials, leaving (n-k+1)/k. So C(n, k) = C(n, k-1) * (n-k+1) / k. Starting from C(n, 0) = 1 and chaining this ratio reproduces every coefficient in the row. The integer division is exact at each step because C(n, k) is always a whole number.
i from 0 to numRows - 1:[1].j from 1 to i, compute the next value as previousValue * (i - j + 1) / j.