Leetcode 119. Pascals Triangle II
Given an integer rowIndex
, return the rowIndex
-th (0-indexed) row of the Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two directly above it as shown:
Example:
Input: rowIndex = 3
Output: [1,3,3,1]
rowIndex
?
rowIndex
<= 33.To compute the rowIndex
-th row of Pascal’s triangle efficiently:
[1]
.Here’s a C++ function implementing the described strategy:
#include <vector>
std::vector<int> getRow(int rowIndex) {
// Create a vector initialized with 0s except for the first element.
std::vector<int> row(rowIndex + 1, 0);
row[0] = 1; // The first element is always 1
// Compute the rowIndex-th row
for (int i = 1; i <= rowIndex; ++i) {
// Update the row from the end to the beginning
for (int j = i; j > 0; --j) {
row[j] += row[j - 1];
}
}
return row;
}
row
of size rowIndex + 1
is initialized with zeros, and the first element is set to 1.1
to rowIndex
, representing the current row being computed.O(rowIndex^2)
O(rowIndex)
rowIndex + 1
is used for the result.This efficient approach ensures that we generate the desired row of Pascal’s triangle without constructing the entire triangle.
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?