




Sponsored
Sponsored
This approach involves generating Pascal's Triangle row by row using an iterative method. The first row is initialized with [1], and for each subsequent row, the first and last element are always 1. The intermediate elements are calculated as sums of appropriate elements from the previous row.
Time Complexity: O(numRows^2) due to the nested loop structure.
Space Complexity: O(numRows^2) as we store all elements of the triangle.
1function generate(numRows) {
2    const triangle = [];
3    for (let i = 0; i < numRows; i++) {
4        const row = new Array(i + 1).fill(1);
5        for (let j = 1; j < i; j++) {
6            row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
7        }
8        triangle.push(row);
9    }
10    return triangle;
11}
12
13const numRows = 5;
14console.log(generate(numRows));
15This JavaScript function builds Pascal's Triangle iteratively. Each row is an array filled with 1s, and inner values are updated based on the values above from the prior row. The triangle is constructed as an array of arrays.
This approach constructs Pascal's Triangle using recursion by calculating each value based on the combination formula. The values on the edges are always 1, and other values are calculated as combinatorial numbers derived recursively.
Time Complexity: O(numRows^3) due to recursive calls, not optimal.
Space Complexity: O(numRows^2) for storing the triangle.
1
In Python, a combination function computes each element of the triangle recursively using combinatorial logic. Each call calculates a combination's value, rapidly constructing Pascal's Triangle row by row.