




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.
1#include <iostream>
#include <vector>
int combination(int n, int k) {
    if (k == 0 || k == n) return 1;
    return combination(n - 1, k - 1) + combination(n - 1, k);
}
std::vector<std::vector<int>> generate(int numRows) {
    std::vector<std::vector<int>> triangle(numRows);
    for (int i = 0; i < numRows; i++) {
        triangle[i] = std::vector<int>(i + 1);
        for (int j = 0; j <= i; j++) {
            triangle[i][j] = combination(i, j);
        }
    }
    return triangle;
}
int main() {
    int numRows = 5;
    std::vector<std::vector<int>> result = generate(numRows);
    for (const auto& row : result) {
        for (int value : row) {
            std::cout << value << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
This C++ approach defines a recursive function that calculates each entry according to Pascal's combination principles. Recursive function calls compute combination values used in constructing each row incrementally.