




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.
1using System.Collections.Generic;
public class PascalTriangleRecursive {
    public static int Combination(int n, int k) {
        if (k == 0 || k == n) return 1;
        return Combination(n - 1, k - 1) + Combination(n - 1, k);
    }
    public static List<List<int>> Generate(int numRows) {
        List<List<int>> triangle = new List<List<int>>();
        for (int i = 0; i < numRows; i++) {
            List<int> row = new List<int>();
            for (int j = 0; j <= i; j++) {
                row.Add(Combination(i, j));
            }
            triangle.Add(row);
        }
        return triangle;
    }
    public static void Main(string[] args) {
        int numRows = 5;
        List<List<int>> result = Generate(numRows);
        foreach (var row in result) {
            Console.WriteLine(string.Join(" ", row));
        }
    }
}
This C# program uses a recursive function to obtain Pascal's Triangle values by calculating each position's combinatorial value. Recursive computation helps build each row of the triangle effectively from the top down.