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.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
1 | |
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Explanation 1
-
Similar to 118. Pascal’s Triangle, we can use the formula to calculate all numbers in a specific row.
-
$currVal = prevVal * (currRow - prevCol) / prevCol$ (Row index and column index start from 1).
Solution 1
1 | |
Explanation 2
-
If
rowIndex = n, then the result will have lengthn + 1. Initially, we create the result list that has lengthn + 1and set all elements to be 1. -
If
curRowIndex = 2, then initially we haveres = [1, 1, 1]. Then we start updating index fromcurRowIndex - 1which is 1 to beres[1] = res[1] + res[0] = 2. Now, we getres = [1, 2, 1]. -
If
rowIndex = 3and we already solverowIndex = 2using the above method, and we haveres = [1, 2, 1, 1]. Foristarting fromcurRowInex - 1down to 1, we updateres[i] = res[i] + res[i-1], then we have wheni = 2,res = [1, 2, 3, 1]; wheni = 1,res = [1, 3, 3, 1].
Solution 2
1 | |