Pascal's Triangle
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.
- 1 <= numRows <= 30
numRows = 5[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]numRows = 1[[1]]numRows = 3[[1],[1,1],[1,2,1]]Building Pascal's Triangle means generating a series of rows where each number is the sum of the two numbers centered directly above it. The challenge is to compute these values efficiently without recalculating the same "parent" numbers over and over.
The most basic way to find any cell (row, col) is to recursively call a function for the two cells above it. However, this is incredibly slow because it recalculates the same cells thousands of times.
def get_val(r, c):
if c == 0 or c == r: return 1
return get_val(r-1, c-1) + get_val(r-1, c)Instead of recomputing the same values, we can build the triangle row-by-row. Every number we calculate is stored in a list, so when we move to the next row, its "parents" are already waiting for us in memory.
We build the triangle iteratively.
- The first and last elements of every row are always 1.
- For every middle index, the value is the sum of prev[j-1] + prev[j].
triangle = [[1]]
for i in range(1, num_rows):
prev = triangle[i-1]
curr = [1]
for j in range(1, i):
curr.append(prev[j-1] + prev[j])
curr.append(1)
triangle.append(curr)
return triangleTriangle Construction
RECURRENCE RELATION
Each cell (i, j) = Cell (i-1, j-1) + Cell (i-1, j). This symmetry builds the entire structure from the edges inward.
EFFICIENCY
We process O(N²) cells in total. By building layer by layer, we avoid redundant calculations—the core of Dynamic Programming.