LeetCode: Pascal's Triangle II Solution
Calculate Pascal's Triangle at a specific rowApproach
Build Pascal's Triangle of rowIndex + 1
rows
Get the last row
Implementation
1var getRow = function (rowIndex) {2 const numRows = rowIndex + 134 const res = [[1]]56 for (let rowIndex = 1; rowIndex < numRows; rowIndex++) {7 const row = Array.from(8 { length: rowIndex + 1 },9 (_, elIndex) =>10 (res[rowIndex - 1][elIndex] || 0) +11 (res[rowIndex - 1][elIndex - 1] || 0)12 )13 res.push(row)14 }1516 return res.pop()17}
Implementation (O(rowIndex)
space)
In-place replacement based on previous state
1i = 1: 1 0 0 02i = 2: 1 1 0 03i = 3: 1 2 1 04i = 4: 1 3 3 1
1var getRow = function (rowIndex) {2 const numRows = rowIndex + 13 const res = Array(numRows).fill(0)4 res[0] = 156 for (let i = 1; i < numRows; i++) {7 for (let j = i; j >= 1; j--) {8 res[j] += res[j - 1]9 }10 }1112 return res13}
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: Pascal's Triangle
How to write Pascal Triangle in plain JavaScript
Previous Post
LeetCode: Concatenation of Array
.concat() or spread operator