Question:
Given a non-negative index k where k ≤ 33, return the k 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]
Solution:
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
let result=[];
for(let i=0; i<rowIndex+1; i++){
let item = [1]; //第一个元素
if(i===1){
item.push(1); //第二行
}
if(i>1){
//循环上一个数组
let arr = result[i-1];
let sum;
for(let j=0 ; j<arr.length-1; j++){
sum = (arr[j]-0)+(arr[j+1]-0);
item.push(sum);
}
item.push(1);//最后一个元素
}
result.push(item);
}
return result[rowIndex];
};
Runtime: 52 ms, faster than 89.39% of JavaScript online submissions for Pascal’s Triangle II.