美文网首页
118. Pascal's Triangle(JS)

118. Pascal's Triangle(JS)

作者: 菁卡因 | 来源:发表于2018-09-03 14:02 被阅读0次

语言:Javascript
内容: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.
方法:每一个结果,前后固定为1,中间为上一个数组的两两相加
例如:arr[2] = [1,1] arr[3] = [1,2,1] arr[4]=[1,3,3,1]


Pascal's Triangle.png
/*
   @param {number} numRows
   @return {number[][]}
*/
 var generate = function(numRows) {
    if(numRows === '') return '';
    if(numRows === 0) return [];
    if(numRows === 1) return [[1]];
    if(numRows === 2) return [[1],[1,1]];
    var res = [[1],[1,1]];
    var temp = [1,1];
    for(var i=3;i<=numRows;i++){
        var arr = temp.slice();
        for(var j=0;j<temp.length-1;j++){
            var num = temp[j]+temp[j+1];
            arr[j+1] = num;
        }
        arr.push(1);
        res.push(arr);
        temp = arr;
    }
    return res;
};

相关文章

网友评论

      本文标题:118. Pascal's Triangle(JS)

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