Problem
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.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Solution
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
var i = 0;
var j = 0;
var res = [];
for (i = 0; i < numRows; i++) {
res.push(Array(i + 1));
for (j = 0; j <= i; j++) {
if (j === 0 || j === i) {
res[i][j] = 1;
} else {
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
}
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n^2).
- Space complexity : O(n^2).