Pascal's Triangle II

Pascal's Triangle II

Sergei Golitsyn

https://leetcode.com/problems/pascals-triangle-ii/

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Solution:

Let's start. We see that the zero level always has one element in the list [1]. The second level always has two elements in the array [1,1]. Based on these conditions, we can calculate the next levels.

We should fill elements from 1 position till the length - 2. Or till the previous level size() - 1. Yes, we can use the previous level size =)

  public static List<Integer> getRow(int rowIndex) {
    if (rowIndex == 0){
      return List.of(1);
    }
    if(rowIndex == 1){
      return List.of(1, 1);
    }

    List<List<Integer>> triangle = new ArrayList();
    triangle.add(List.of(1));
    triangle.add(List.of(1, 1));

    for(int i = 2; i <= rowIndex; i++){
      List<Integer> tmp = new ArrayList<>();
      tmp.add(1);
      List<Integer> prevList = triangle.get(i - 1);
      for (int j = 1; j < prevList.size(); j++){

        int a = prevList.get(j - 1) + prevList.get(j);
        tmp.add(a);
      }
      tmp.add(1);
      triangle.add(tmp);
    }
    return triangle.get(rowIndex);
  }

Report Page