# LeetCode: Pascal's Triangle II Solution

Calculate Pascal's Triangle at a specific row

## Approach

Build Pascal's Triangle of

rowIndex + 1
rows

Get the last row

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var getRow = function (rowIndex) {2  const numRows = rowIndex + 13
4  const res = [[1]]5
6  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  }15
16  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] = 15
6  for (let i = 1; i < numRows; i++) {7    for (let j = i; j >= 1; j--) {8      res[j] += res[j - 1]9    }10  }11
12  return res13}```

leetcode

array

## Next Post

LeetCode: Pascal's Triangle

Aug 29, 2021

How to write Pascal Triangle in plain JavaScript

## Previous Post

LeetCode: Concatenation of Array

Aug 28, 2021

.concat() or spread operator

Search Posts