Leetcode 118. Pascal’s Triangle
Given an integer numRows
, return the first numRows
of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example:
Input: numRows = 5
Output: [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]
]
numRows
is guaranteed to be a positive integer.n
rows is ( \frac{n(n + 1)}{2} ), which is (O(numRows^2)).#include <vector>
using namespace std;
vector<vector<int>> generate(int numRows) {
vector<vector<int>> pascalTriangle;
for (int i = 0; i < numRows; ++i) {
vector<int> row(i + 1, 1); // initialize row with 1s
for (int j = 1; j < i; ++j) {
row[j] = pascalTriangle[i - 1][j - 1] + pascalTriangle[i - 1][j];
}
pascalTriangle.push_back(row);
}
return pascalTriangle;
}
This implementation initializes each row with 1s and uses a nested loop to fill in the middle elements correctly based on the values from the previous row. It ensures that the output is in the correct format representing Pascal’s triangle up to the given number of rows.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?