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; }
0 comments:
Post a Comment