118. Pascal's Triangle(JS)

2018-09-03  本文已影响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;
};
上一篇 下一篇

猜你喜欢

热点阅读