LeetCode: Pascal's Triangle Solution

How to write Pascal Triangle in plain JavaScript

Approach

Follow this pseudo formula

1currentRow[i] = previousRow[i] + previousRow[i - 1]

Implementation

1var generate = function (numRows) {
2 const res = [[1]]
3
4 for (let rowIndex = 1; rowIndex < numRows; rowIndex++) {
5 const row = Array.from(
6 { length: rowIndex + 1 },
7 (_, elIndex) =>
8 (res[rowIndex - 1][elIndex] || 0) +
9 (res[rowIndex - 1][elIndex - 1] || 0)
10 )
11 res.push(row)
12 }
13
14 return res
15}

Comments

Loading comments...

Tags

leetcode

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Majority Element

Aug 30, 2021

Boyer-Moore Voting Algorithm

Previous Post

LeetCode: Pascal's Triangle II

Aug 29, 2021

Calculate Pascal's Triangle at a specific row

HoningJS

Search Posts