




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.
1using System;
2using System.Collections.Generic;
3
4public class PascalTriangle {
5    public static List<List<int>> Generate(int numRows) {
6        List<List<int>> triangle = new List<List<int>>();
7        for (int i = 0; i < numRows; i++) {
8            List<int> row = new List<int>();
9            row.Add(1);
10            for (int j = 1; j < i; j++) {
11                row.Add(triangle[i - 1][j - 1] + triangle[i - 1][j]);
12            }
13            if (i > 0) row.Add(1);
14            triangle.Add(row);
15        }
16        return triangle;
17    }
18
19    public static void Main(String[] args) {
20        int numRows = 5;
21        List<List<int>> result = Generate(numRows);
22        foreach (var row in result) {
23            Console.WriteLine(string.Join(" ", row));
24        }
25    }
26}
27For this C# implementation, we leverage List to create each row of Pascal's Triangle. Each row starts and ends with 1, and intermediate values are computed using the values from the preceding row. The complete triangle is stored as a list of lists.
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.