1. Individual Cell Combinations Formula (nCr)
Intuition
Compute each cell triangle[r][c] independently using the factorial combinatorial formula nCr.
Algorithm
- 1. For each row r from 0 to numRows - 1: - For each col c from 0 to r: - Compute cell value via combination nCr(r, c). - Add row to triangle.
- 2. Return triangle.
Combinations Formula nCr Trace for numRows = 5
2 of 2 questions left todayPhase 1 — Setup & Combinations Principle: For numRows = 5, every cell (r, c) is calculated independently using combinations formula nCr = r
Phase 1 — Setup & Combinations Principle: For numRows = 5, every cell (r, c) is calculated independently using combinations formula nCr = r! / (c! * (r - c)!). We trace constructing the 4th row (r = 3, target 4 elements).
#include <iostream>#include <vector> using namespace std; class Solution { long long nCr(int n, int r) { long long res = 1; for (int i = 0; i < r; ++i) { res = res * (n - i); res = res / (i + 1); } return res; }public: vector<vector<int>> generate(int numRows) { vector<vector<int>> res; for (int r = 0; r < numRows; ++r) { vector<int> row; for (int c = 0; c <= r; ++c) { row.push_back(nCr(r, c)); } res.push_back(row); } return res; }}; int main() { Solution sol; int numRows = 5; vector<vector<int>> result = sol.generate(numRows); cout << "Pascal's Triangle (numRows = " << numRows << "):" << endl; for (const auto& row : result) { cout << "["; for (size_t i = 0; i < row.size(); ++i) { cout << row[i] << (i + 1 < row.size() ? ", " : ""); } cout << "]" << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(N^3)— Computing nCr for each cell takes O(N). Sum of cells is O(N2), so total time is O(N3). - Space complexity:
O(1)— Auxiliary space is O(1) beyond output matrix.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.