Pascal's Triangle

easy
math
combinatorics
arrays

Given an integer numRows, return the first numRows rows of Pascal's triangle. In Pascal's triangle each number is the sum of the two numbers directly above it, and every row starts and ends with 1.

Input / output

  • Input: numRows: integer
  • Output: a list of numRows lists, each row of the triangle

Examples

  1. numRows = 5 returns [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].
  2. numRows = 1 returns [[1]].
  3. numRows = 2 returns [[1],[1,1]].

Constraints

  • 1 <= numRows <= 30

Follow-up Row k (0-indexed) is exactly the binomial coefficients C(k, 0..k). Can you generate each row from the previous one using only additions, without recomputing factorials?

Examples

Example 1

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2

Input: numRows = 1
Output: [[1]]

Example 3

Input: numRows = 2
Output: [[1],[1,1]]
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.