DEV Community

codingpineapple
codingpineapple

Posted on

118. Pascal's Triangle (javascript solution)

Description:

Given an integer numRows, return the first numRows of Pascal's triangle.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// Dynamic programming approach (tabulation)
// Use values in the previous row of the table to calculate the values of the next row
var generate = function(numRows) {
    const table = [];
    for (let i = 0; i < numRows; i++) {
        table[i] = [];
        table[i][0] = 1;
        for (let j = 1; j < i; j++) {
            table[i][j] = table[i-1][j-1] + table[i-1][j]
        }
        table[i][i] = 1;
    }
    return table;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)