Description

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:

1            1
2          1   1
3        1   2   1
4      1   3   3   1
5    1   4   6   4   1

Example 1:

1Input: numRows = 5
2Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

1Input: numRows = 1
2Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

Solution

This one requires two iterations.

 1class Solution {
 2    public List<List<Integer>> generate(int numRows) {
 3        List<List<Integer>> result = new java.util.ArrayList<>();
 4        for (int i = 0; i < numRows; i++) {
 5            System.out.println(result);
 6            List<Integer> row = new ArrayList<>();
 7            for (int j = 0; j <= i; j++) {
 8                if (j == 0 || j == i) {
 9                    row.add(1);
10                } else {
11                    List<Integer> prevRow = result.get(i - 1);
12                    row.add(prevRow.get(j - 1) + prevRow.get(j));
13                }
14            }
15            result.add(row);
16        }
17        return result;
18    }
19}