LeetCode 119: Pascal's Triangle II Solution
Master LeetCode problem 119 (Pascal's Triangle II), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
119. Pascal's Triangle II
Problem Explanation
Explanation
To generate the rowIndex-th row of Pascal's Triangle, we can use the property that each element in the triangle is the sum of the two elements directly above it. We can start with the first row [1], then iteratively compute the next row based on the previous row.
We can optimize the space complexity to O(rowIndex) by only storing the current row and updating it in place without needing to store the entire triangle.
- Time complexity: O(rowIndex^2) - we need to compute each element in each row up to rowIndex
- Space complexity: O(rowIndex) - only storing the current row
Solution Code
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>();
for (int i = 0; i <= rowIndex; i++) {
row.add(0, 1); // Add 1 at the beginning of the row
for (int j = 1; j < row.size() - 1; j++) {
row.set(j, row.get(j) + row.get(j + 1)); // Update each element based on the previous row
}
}
return row;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 119 (Pascal's Triangle II)?
This page provides optimized solutions for LeetCode problem 119 (Pascal's Triangle II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 119 (Pascal's Triangle II)?
The time complexity for LeetCode 119 (Pascal's Triangle II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 119 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 119 in Java, C++, or Python.