0118 - Pascal's Triangle
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Examples
Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Input: numRows = 1 Output: [[1]]
Constraints
1 <= numRows <= 30
Java Solution
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
triangle.add(new ArrayList<>());
triangle.get(0).add(1);
for(int row = 1; row < numRows; row++) {
List<Integer> currentRow = new ArrayList<>();
List<Integer> prevRow = triangle.get(row-1);
currentRow.add(1);
for(int j = 1; j < row; j++) {
currentRow.add(prevRow.get(j-1) + prevRow.get(j));
}
currentRow.add(1);
triangle.add(currentRow);
}
return triangle;
}
}
Last updated