118. Pascal’s Triangle Leetcode Java Solution
2 min readMar 21, 2025
Given an integer numRows, return the first numRows of Pascal's triangle.
Get Soham’s stories in your inbox
Join Medium for free to get updates from this writer.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Example 2:
Input: numRows = 1
Output: [[1]]Constraints:
1 <= numRows <= 30
Explanation:
- The index itself indicates number of elements in the list at the current row.
- Using this we will solve this problem. At the beginning, we start with the first row by creating it and storing it in the prev list to use it for the next iterations.
- We do this till we reach n point.
Solution:
class Solution {
public List<List<Integer>> generate(int numRows) {
// Main result storing variable
List<List<Integer>> list = new ArrayList<>();
List<Integer> l = null; // for creating the current list
List<Integer> prev = new ArrayList<>(); // for storing prev list state
for(int i = 1; i <= numRows; i++){
l = new ArrayList<>();
for(int j = 1; j <= i; j++){
if(j == 1 || j == i) l.add(1); // first and last element is one
else l.add(prev.get(j - 2) + prev.get(j - 1)); // others are sum of top two elements (j - 1) + (j - 2)
}
prev = l;
list.add(new ArrayList<>(l));
}
return list;
}
}





