美文网首页
118. Pascal's Triangle

118. Pascal's Triangle

作者: exialym | 来源:发表于2016-09-21 22:49 被阅读15次

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]
]
很常规的思想,构造从第3行开始构造每一个数组,每一个数组只构造前一半。

/**
 * @param {number} numRows
 * @return {number[][]}
 */
var generate = function(numRows) {
    if (numRows===0) {
        return [];
    } else if (numRows===1) {
        return [[1]];
    } else if (numRows===2){
        return [[1],[1,1]];
    } else {
        var a = [[1],[1,1]];
        for (var i=2;i<numRows;i++) {
            a[i]=[];
            a[i][0]=1;
            var tempp = i+1;
            var temp = parseInt(tempp/2);
            for (var j = 1;j<tempp/2;j++) {
                a[i][j] = a[i-1][j-1]+a[i-1][j];
            }
            for (j = temp; j<tempp;j++) {
                a[i][j]=a[i][tempp-1-j];
            }
        }
        return a;
    }
};

相关文章

网友评论

      本文标题:118. Pascal's Triangle

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