Skip to content

Latest commit

 

History

History
91 lines (51 loc) · 1.21 KB

File metadata and controls

91 lines (51 loc) · 1.21 KB

LeetCode – 118. Pascal's Triangle

Problem Statement

Given an integer numRows, generate the first numRows rows of Pascal’s Triangle.
Each number is the sum of the two numbers directly above it.

Description

  • Row starts and ends with 1.

  • Inner numbers follow:
    row[j] = prev_row[j - 1] + prev_row[j]

  • Return as a list of lists.

Input

One integer:

numRows

Output

A 2D list representing Pascal’s Triangle.

Examples

Example 1

Input:

numRows = 5

Output:

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Explanation:
Each row is created using the previous row.

Example 2

Input:

numRows = 1

Output:

[
[1]
]

Constraints

  • 1 ≤ numRows ≤ 30

Hints

  • First and last elements of every row are 1.

  • Each middle element is the sum of two numbers above it.

  • Build one row at a time.

Approach / Explanation

  1. Create an empty result list.

  2. For each row index:

    • Start with all 1s.

    • Update inner elements using previous row.

  3. Append row to the triangle.

Complexity

  • Time: O(numRows²)

  • Space: O(numRows²)