118. Pascal's Triangle
Problem
Tags: Array
, Dynamic Programming
Given an integer numRows
, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
Code
JS
// 118. Pascal's Triangle (11/26/53440)
// Runtime: 64 ms (74.65%) Memory: 38.84 MB (94.11%)
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
let triangle = [];
for(let row = 0; row < numRows; row++) {
let store = [1];
for(let column = 0; column < row - 1; column++) {
store.push(triangle[row - 1][column] + triangle[row - 1][column + 1]);
}
if(row) store.push(1);
triangle.push(store);
}
return triangle;
};