[LeetCode] 119. Pascals Triangle II

Problem

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Note that the row index starts from 0.

119. Pascal's Triangle II

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

1
2
Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

Explanation 1

  1. Similar to 118. Pascal’s Triangle, we can use the formula to calculate all numbers in a specific row.

  2. $currVal = prevVal * (currRow - prevCol) / prevCol$ (Row index and column index start from 1).

Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        res.add(1);

        for (int preCol = 1; preCol < rowIndex+1; preCol++) {
            long preNum = res.get(res.size()-1);
            long curNum = preNum * (rowIndex+1 - preCol) / preCol;
            res.add((int)curNum);
        }

        return res;
    }
}

Explanation 2

  1. If rowIndex = n, then the result will have length n + 1. Initially, we create the result list that has length n + 1 and set all elements to be 1.

  2. If curRowIndex = 2, then initially we have res = [1, 1, 1]. Then we start updating index from curRowIndex - 1 which is 1 to be res[1] = res[1] + res[0] = 2. Now, we get res = [1, 2, 1].

  3. If rowIndex = 3 and we already solve rowIndex = 2 using the above method, and we have res = [1, 2, 1, 1]. For i starting from curRowInex - 1 down to 1, we update res[i] = res[i] + res[i-1], then we have when i = 2, res = [1, 2, 3, 1]; when i = 1, res = [1, 3, 3, 1].

Solution 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < rowIndex + 1; i++) {
            res.add(1);
        }

        for (int curRowIndex = 1; curRowIndex <= rowIndex; curRowIndex++) {
            for (int i = curRowIndex - 1; i >= 1; i--) {
                res.set(i, res.get(i) + res.get(i-1));
            }
        }
        
        return res;
    }
}