Statement▼
Given an integer, numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each element is formed by adding the two numbers directly above it from the previous row. The triangle starts with a single
1 at the top, and each row expands based on this rule.
Constraints:
1
≤ numRows≤ 30
Solution
The core intuition behind the solution is to apply a dynamic programming pattern to construct Pascal’s triangle row by row. Instead of recalculating values independently, each row reuses results from the row above, ensuring efficient computation. This recursive property makes Pascal’s triangle a natural fit for dynamic programming, because each state (row element) depends only on previously computed states. The challenge is to compute the interior values correctly while ensuring the boundary values (first and last elements) remain numRows.
The solution iteratively constructs each row based on the previously computed row to achieve this. Each row’s first and last elements are initialized as
Let’s break down the key steps of the solution:
Create an empty list
triangleto hold all rows of Pascal’s triangle.Iterate through row indexes and for each row number from
0 tonumRows−1 , create a new row of length row number+1 .Set boundary values by assigning
1 to the first and last elements of the row, as every row in Pascal’s triangle begins and ends with1 .Compute the interior values of each row by iterating between the first and last position, and calculate the value as the sum of the two adjacent numbers from the previous row:
row[j]=triangle[row number−1][j−1]+triangle[row number−1][j]
Note: This is the dynamic programming relation: the current value depends on two previously computed values.
After computing the row, add the completed row to the
trianglelist.Once all rows are constructed, return
triangleas the final Pascal’s Triangle.
Let’s look at the following illustration to get a better understanding of the solution: