Problem
Section titled “Problem”You are 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 and the first and last number on each row must be equal to 1, as shown below:

Example 1:
Input: numRows = 5Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Example 2:
Input: numRows = 1Output: [[1]]Constraints:
-
numRows
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”The definition is already a recurrence. Row i (0-indexed) has i + 1 entries; its first and last entries are 1, and every inner entry j is the sum of the two entries above it in row i - 1:
Row i - 1 is complete before row i starts, so building the rows top to bottom always has the needed values ready. (Entry j of row i is the binomial coefficient ; for numRows up to 30 the largest is , which fits in an int.)
Algorithm
Section titled “Algorithm”- Create
trianglewithnumRowsrows. - For each
ifrom0tonumRows - 1, make rowiof sizei + 1filled with1(this sets both ends). - For each inner
jfrom1toi - 1, settriangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]. - Return
triangle.
Complexity
Section titled “Complexity”- Time: for
n = numRows— the triangle has entries and each is computed in . - Space: extra — only the output, which itself has entries.
Edge cases
Section titled “Edge cases”numRows = 1(Example 2): row0is[1]and the inner loop never runs.- Rows 0 and 1 have no inner entries, so they stay all
1s.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> triangle(numRows); for (int i = 0; i < numRows; i++) { triangle[i].assign(i + 1, 1); for (int j = 1; j < i; j++) { triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; } } return triangle; }};class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> triangle = new ArrayList<>(numRows); for (int i = 0; i < numRows; i++) { List<Integer> row = new ArrayList<>(i + 1); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { row.add(1); } else { List<Integer> above = triangle.get(i - 1); row.add(above.get(j - 1) + above.get(j)); } } triangle.add(row); } return triangle; }}class Solution: def generate(self, numRows: int) -> list[list[int]]: triangle = [] for i in range(numRows): row = [1] * (i + 1) for j in range(1, i): row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j] triangle.append(row) return triangleGive it a try first
Attempt the problem on LeetCode — the code will still be here.