Search⌘ K
AI Features

Solution Review: Pascal's Triangle

Explore how to implement a recursive function to generate each row of Pascal's Triangle by using base cases and the previous row's values. Understand the process of building the triangle step-by-step through recursive calls and accumulation in JavaScript. This lesson helps you gain practical skills in recursion with numerical problems relevant to coding interviews.

We'll cover the following...

Solution: Using Recursion

Javascript (babel-node)
function printPascal(testVariable) {
// Base case
if (testVariable == 0) {
return [1];
}
else {
var line = [1];
// Recursive case
previousLine = printPascal(testVariable - 1);
for (let i = 0; i < previousLine.length - 1; i++) {
line.push(previousLine[i] + previousLine[i + 1]);
}
line.push(1);
}
return line;
}
// Driver Code
var testVariable = 5;
console.log(printPascal(testVariable));

Explanation:

Each row in Pascal’s triangle starts with a 11, and ends with a 11 ...