Leetcode 118. Pascal’s Triangle
Given an integer numRows
, generate the first numRows
of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Here is an example of the first 5 rows of Pascal’s triangle:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
numRows
is zero?
[]
.numRows
?
numRows
considered valid input?
numRows
will always be a non-negative integer.result
to store the rows of Pascal’s triangle.[1]
and iterate from the second row up to numRows
.1
.1
and append it to the result
.result
list.O(n)
.O(numRows^2)
.import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
// First base row
List<Integer> row = new ArrayList<>();
row.add(1);
result.add(new ArrayList<>(row));
for (int i = 1; i < numRows; i++) {
List<Integer> prevRow = result.get(result.size() - 1);
row = new ArrayList<>();
row.add(1); // first element
// middle elements
for (int j = 1; j < prevRow.size(); j++) {
row.add(prevRow.get(j - 1) + prevRow.get(j));
}
row.add(1); // last element
result.add(row);
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.generate(5));
}
}
result
is the final list of lists that will hold all the rows.numRows
is 0, we return an empty list.[1]
.numRows
:
result
.[1]
.[1]
.result
.This code ensures that the Pascal’s Triangle is built row by row with each element dependent on the values directly above it, conforming to the defined properties.
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?