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:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Solution 1
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
var res = [];
var i = 0;
var j = 0;
for (i = 0; i <= rowIndex; i++) {
res.unshift(1);
for (j = 1; j < i; j++) {
res[j] += res[j + 1];
}
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n^2).
- Space complexity : O(n).
Solution 2
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
var res = Array(rowIndex + 1);
var i = 0;
var j = 0;
for (i = rowIndex; i >= 0; i--) {
res[i] = 1;
for (j = i + 1; j < rowIndex; j++) {
res[j] += res[j + 1];
}
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n^2).
- Space complexity : O(n).
Solution 3
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
var res = Array(rowIndex + 1);
res[0] = 1;
for (var i = 1; i <= rowIndex; i++) {
res[i] = res[i - 1] * ((rowIndex - i + 1) / i);
}
return res;
};
Explain:
在第 k
行,第 i
个元素,res[i] = res[i - 1] * ((k - i + 1) / i)
。
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).