




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.
1def generate(numRows):
2    triangle = []
3    for i in range(numRows):
4        row = [1] * (i + 1)
5        for j in range(1, i):
6            row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
7        triangle.append(row)
8    return triangle
9
10if __name__ == '__main__':
11    numRows = 5
12    result = generate(numRows)
13    for row in result:
14        print(row)
15This Python function constructs Pascal's Triangle by initializing each row with 1s, then updating middle values using the sum of two values from the previous row. It returns a list of lists representing the triangle.
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;
using 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.