Question:
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Solution:
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
if(numRows===1)return[[1]];
//第一个元素和最后一个元素必然是1
let result=[];
for(let i=0; i<numRows; 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;
}
Runtime: 48 ms, faster than 100.00% of JavaScript online submissions for Pascal’s Triangle.