Problem Description
Given an integer rowIndex
, return the rowIndexth
(0-indexed) row of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Examples
Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] Example 3: Input: rowIndex = 1 Output: [1,1]
Python Solution
def getRow(rowIndex: int) -> List[int]:
# Initialize row with 1
row = [1]
for i in range(rowIndex):
# Calculate new row in-place from right to left
for j in range(i, 0, -1):
row[j] = row[j] + row[j-1]
# Add new 1 at the end
row.append(1)
return row
Java Solution
class Solution {
public List getRow(int rowIndex) {
List row = new ArrayList<>();
row.add(1);
for (int i = 0; i < rowIndex; i++) {
// Calculate new row in-place from right to left
for (int j = i; j > 0; j--) {
row.set(j, row.get(j) + row.get(j-1));
}
// Add new 1 at the end
row.add(1);
}
return row;
}
}
C++ Solution
class Solution {
public:
vector getRow(int rowIndex) {
vector row = {1};
for (int i = 0; i < rowIndex; i++) {
// Calculate new row in-place from right to left
for (int j = i; j > 0; j--) {
row[j] = row[j] + row[j-1];
}
// Add new 1 at the end
row.push_back(1);
}
return row;
}
};
JavaScript Solution
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
const row = [1];
for (let i = 0; i < rowIndex; i++) {
// Calculate new row in-place from right to left
for (let j = i; j > 0; j--) {
row[j] = row[j] + row[j-1];
}
// Add new 1 at the end
row.push(1);
}
return row;
};
C# Solution
public class Solution {
public IList GetRow(int rowIndex) {
IList row = new List { 1 };
for (int i = 0; i < rowIndex; i++) {
// Calculate new row in-place from right to left
for (int j = i; j > 0; j--) {
row[j] = row[j] + row[j-1];
}
// Add new 1 at the end
row.Add(1);
}
return row;
}
}
Complexity Analysis
- Time Complexity: O(n²) where n is rowIndex
- Space Complexity: O(n) to store the row
Solution Explanation
This solution uses an optimized in-place approach:
- Key concept:
- Single array reuse
- Right-to-left updates
- Constant space
- Algorithm steps:
- Start with [1]
- Update values in-place
- Add trailing 1
- Repeat for each row
Key points:
- Space optimization
- In-place updates
- Right-to-left order
- No extra storage