Pascal's Triangle

Build the first numRows of Pascal's Triangle — row[j] = prevRow[j-1] + prevRow[j].

Easy
Time O(n^2) Space O(n^2)
LeetCode
2 min read
dp combinatorics

Problem#

Return the first numRows rows of Pascal’s Triangle.

Examples#

  • numRows = 5[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Constraints#

  • 1 <= numRows <= 30.

Approach#

Iterative build row by row.

Solution#

Pascal's Triangle
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> out;
for (int i = 0; i < numRows; ++i) {
vector<int> row(i + 1, 1);
for (int j = 1; j < i; ++j) row[j] = out[i - 1][j - 1] + out[i - 1][j];
out.push_back(move(row));
}
return out;
}
};

Editorial#

The literal recurrence. Boundary cells [0] and [i] are always 1; interior cells are sums of two above.

Complexity#

  • Time: O(n²).
  • Space: O(n²).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.