A solution to leetcode Problem 118. Pascal’s Triangle in JavaScript in JavaScript
Pascal’s Triangle is a problem that asks us to generate the first n rows of Pascal’s Triangle. Pascal’s Triangle is a triangular array of integers that is formed by starting with a row of 1 and then adding the two numbers above it to get the next row.
Problem Statement:
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
Solution
To solve this problem in JavaScript, we can use a loop to generate the rows of Pascal’s Triangle. We can start by initializing an empty array called a “triangle” and then pushing the first row of 1 into it. Then, we can use a for loop to iterate through the number of rows we want to generate.
Inside the for loop, we can initialize a new row called “currentRow” and set it equal to an array of 1s with the same length as the current loop iteration + 1. Then, we can use another loop to iterate through the elements of the current row, starting at index 1 and ending at the second to last element. Inside this inner loop, we can set the value of the current element equal to the sum of the previous element in the current row and the element in the previous row at the same index.
Finally, we can push the current row into the triangle array and return the triangle array once the outer loop has been completed.
Here is the complete solution in JavaScript:
const generate = (numRows) => {
const triangle = [];
if (numRows === 0) {
return triangle;
}
triangle.push([1]);
for (let i = 1; i < numRows; i++) {
const currentRow = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
currentRow[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
triangle.push(currentRow);
}
return triangle;
};
This solution has a time complexity of O(n^2), as we have a nested loop that both have a time complexity of O(n).
I hope this solution helps you understand how to solve Leetcode 118. Pascal’s Triangle in JavaScript. Happy coding!
Real excellent information can be found on site.Raise blog range