118. Pascal's Triangle

Description:

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

My code:

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    let pascalTriangle = [], tempArr = [];
    for(let i = 1; i <= numRows; i++) {
        tempArr = [];
        for(let j = 0; j < i; j++) {
            if(j == 0 || j == i - 1) {
                tempArr.push(1);
            } else {
                //处理除了第一位和最后一位的
                tempArr[j] = pascalTriangle[i - 2][j - 1] + pascalTriangle[i - 2][j];
            }
        }
            pascalTriangle.push(tempArr);
    }
    return pascalTriangle;
};

你可能感兴趣的:(118. Pascal's Triangle)