




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.
1#include <iostream>
2#include <vector>
3
4std::vector<std::vector<int>> generate(int numRows) {
5    std::vector<std::vector<int>> triangle(numRows);
6    for (int i = 0; i < numRows; i++) {
7        triangle[i].resize(i + 1);
8        triangle[i][0] = 1;
9        triangle[i][i] = 1;
10        for (int j = 1; j < i; j++) {
11            triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
12        }
13    }
14    return triangle;
15}
16
17int main() {
18    int numRows = 5;
19    std::vector<std::vector<int>> result = generate(numRows);
20    for (const auto& row : result) {
21        for (int num : row) {
22            std::cout << num << " ";
23        }
24        std::cout << std::endl;
25    }
26    return 0;
27}
28In this C++ implementation, we utilize the vector container to create a 2D vector representing the Pascal's Triangle. Each row is resized to the appropriate size and populated, with the ends set to 1 and the middle calculated as the sum of elements from the previous row.
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
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.