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 numbers directly above it as shown:
Example:
Input: rowIndex = 3
Output: [1, 3, 3, 1]
Input: rowIndex = 0
Output: [1]
Input: rowIndex = 1
Output: [1, 1]
rowIndex
? Typically it will be non-negative.For now, we will assume rowIndex
is a non-negative integer and not extraordinarily large for normal computational purposes.
[1]
.rowIndex
row and return it.We will use a single list and update it in place to maintain constant space complexity for this iterative approach.
import java.util.*;
public class PascalTriangleII {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>();
row.add(1); // First row is always [1]
for (int i = 1; i <= rowIndex; i++) {
for (int j = row.size() - 1; j >= 1; j--) {
row.set(j, row.get(j) + row.get(j - 1));
}
row.add(1); // Add the ending '1' for each row
}
return row;
}
public static void main(String[] args) {
PascalTriangleII solution = new PascalTriangleII();
System.out.println(solution.getRow(3)); // Output: [1, 3, 3, 1]
System.out.println(solution.getRow(0)); // Output: [1]
System.out.println(solution.getRow(1)); // Output: [1, 1]
}
}
The time complexity of this solution is O(rowIndex^2), where rowIndex
is the given input. This is due to the nested loop structure where we have to update the list for each row up to rowIndex
.
The space complexity is O(rowIndex) because we use a single list to store the current row of Pascal’s triangle, and its size grows linearly with rowIndex
.
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?