Problem

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

Example

numRows = 5, the result should be:

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

JavaScript Code

function generate(numRows) {
    var result = [];
    if (numRows <= 0)
           return result;
 
    var pre = [];
    pre.push(1);
    result.push(pre);
 
    for (var i = 2; i <= numRows; i++) {
        var cur = [];
 
        cur.push(1); //first
        for (var j = 0; j < pre.length - 1; j++) {
            cur.push(pre[j] + pre[j + 1]); //middle
        }
        cur.push(1);//last
 
        result.push(cur);
        pre = cur;
    }
    return result;
}

1 comment:

  1. Custom Data Cable - Alfa Chemistry is committed to the development and manufacturing of optical components, optical fiber products and light sources, and provides high-quality, fast and economical services to universities, scientific research institutes, optical companies and optical device R&D institutions. Alfa Chemistry has experienced experts, advanced equipment laboratories, analysis rooms, and pilot test equipment, which can meet customers' needs for high-quality optical products and services of different scales.

    ReplyDelete

Blogroll

Popular Posts