Question:

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

118. Pascal's Triangle - 图1
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

  1. Input: 5
  2. Output:
  3. [
  4. [1],
  5. [1,1],
  6. [1,2,1],
  7. [1,3,3,1],
  8. [1,4,6,4,1]
  9. ]

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.