118. Pascal's Triangle (javascript solution)

cod3pineapple

codingpineapple

Posted on March 1, 2021

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
💖 💪 🙅 🚩
cod3pineapple
codingpineapple

Posted on March 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related