Skip to main content

Pascal's Triangle II

Problem statement

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: rowIndex = 3Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0Output: [1]

Example 3:

Input: rowIndex = 1Output: [1,1]

Constraints:

  • 0 <= rowIndex <= 33

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

My solution

/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
if (rowIndex === 0) {
return [1]
}
if (rowIndex === 1) {
return [1, 1]
}

let count = 2;
let answer = [1, 1]

while (count <= rowIndex) {
answer = [1, ...generate(answer), 1];
count++
// console.log("answer", answer)
}

return answer
};

function generate(arr) {
const retArr = []
for (let i = 0; i < arr.length - 1; i++) {
// console.log(`${i} => ${arr[i]}:${arr[i + 1]}`)
retArr.push(arr[i] + arr[i + 1])
}

// console.log(retArr)
// console.log("----")
return retArr
}