Hone logo
Hone
Problems

Pascal's Triangle Generation

Pascal's Triangle is a triangular array of binomial coefficients. It has many fascinating mathematical properties and is often used in combinatorics and probability. Your task is to generate a specified number of rows of Pascal's Triangle.

Problem Description

You are tasked with creating a function that generates Pascal's Triangle up to a given number of rows. Each number in Pascal's Triangle is the sum of the two numbers directly above it. The edges of the triangle are always 1.

Requirements:

  • The function should accept a single integer, numRows, representing the number of rows to generate.
  • The output should be a list of lists (or a 2D array), where each inner list represents a row of Pascal's Triangle.
  • The first row should contain a single 1.
  • Each subsequent row should be constructed based on the row above it.

Expected Behavior:

  • For numRows = 1, the output should be [[1]].
  • For numRows = 5, the output should be [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]].

Edge Cases:

  • If numRows is 0 or negative, the function should return an empty list.

Examples

Example 1:

Input: numRows = 1
Output: [[1]]
Explanation: The triangle has only one row, which is [1].

Example 2:

Input: numRows = 5
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Explanation:
Row 1: [1]
Row 2: [1, 1] (1 is from the previous row's 1, the next 1 is also from the previous row's 1)
Row 3: [1, 2, 1] (1, then 1+1=2, then 1)
Row 4: [1, 3, 3, 1] (1, then 1+2=3, then 2+1=3, then 1)
Row 5: [1, 4, 6, 4, 1] (1, then 1+3=4, then 3+3=6, then 3+1=4, then 1)

Example 3:

Input: numRows = 0
Output: []
Explanation: No rows are requested, so an empty list is returned.

Constraints

  • 0 <= numRows <= 30
  • The input numRows will be an integer.
  • The generated numbers within the triangle will fit within standard integer types.

Notes

  • Think about how each element in a row is related to the elements in the preceding row.
  • Consider the base cases for constructing the triangle.
  • You can iterate through the rows and build each row dynamically based on the one before it.
Loading editor...
plaintext