Skip to main content

5 posts tagged with "dp"

View All Tags

· One min read

https://leetcode.com/problems/pascals-triangle/

Solution 1

/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function (numRows) {
if (numRows === 1) {
return [[1]];
}

if (numRows === 2) {
return [[1], [1, 1]];
}

let rows = [[1], [1, 1]];

for (let i = 2; i < numRows; i++) {
let prevRow = rows[i - 1];

let currentRow = [1];
for (let j = 0; j < prevRow.length - 1; j++) {
currentRow.push(prevRow[j] + prevRow[j + 1]);
}
currentRow.push(1);

rows.push(currentRow);
}
return rows;
};

· One min read

https://leetcode.com/problems/pascals-triangle-ii/

Solution 1

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

if (rowIndex === 1) {
return [1, 1];
}

let rows = [[1], [1, 1]];

for (let i = 2; i <= rowIndex; i++) {
let prevRow = rows[i - 1];

let currentRow = [1];

for (let j = 0; j < prevRow.length - 1; j++) {
currentRow.push(prevRow[j] + prevRow[j + 1]);
}
currentRow.push(1);

rows.push(currentRow);
}

return rows[rowIndex];
};