← All problems

118. Pascals Triangle

EasyOpen on LeetCodeProblem statement

Problem Statement

118. Pascal's Triangle

Easy


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:

 

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:

Java

Source file
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> tri = new ArrayList<>();
        tri.add(List.of(1));
        for (int i = 1; i < numRows; i++) {
            List<Integer> row = new ArrayList<>();
            row.add(1);
            List<Integer> prev = tri.get(tri.size() - 1);
            for (int j = 1; j < prev.size(); j++)
                row.add(prev.get(j - 1) + prev.get(j));
            row.add(1);
            tri.add(row);
        }
        return tri;
    }
}