Categories
Dynamic Programming Leetcode Loop

Unique Paths (Iterative)

let uniquePaths = function(m, n) {

let getKey = (row, col) => `${row}${col}`;

let cache = { }
for (let row = 1; row <= m; row++) {
for (let col = 1; col <= n; col++) {
if (row === 1) {
cache[getKey(row, col)] = 1;
}
else if (col === 1) {
cache[getKey(row, col)] = 1;
}
else {
cache[getKey(row, col)] = cache[getKey(row-1, col)] + cache[getKey(row, col - 1)];
}
}
}

return cache[getKey(m,n)];
};

Leave a Reply

Your email address will not be published. Required fields are marked *