




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.
1def
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.