美文网首页
118. Pascal's Triangle

118. Pascal's Triangle

作者: Icytail | 来源:发表于2017-11-17 00:02 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/eacdvxtx.html