Number of Ways to Stay in the Same Place After Some Steps LeetCode solution in JavaScript

1
var numWays = function (steps, arrLen) {
2
let memo = Array(steps + 1)
3
.fill(0)
4
.map(() => Array(steps + 1).fill(-1)),
5
mod = 10 ** 9 + 7;
6
return dp(0, steps);
7

8
function dp(i, steps) {
9
if (steps === 0) return i === 0 ? 1 : 0; // found a way
10
if (i > steps || i < 0 || i >= arrLen) return 0; // out of bounds
11
if (memo[i][steps] !== -1) return memo[i][steps]; // memoized
12

13
let moveLeft = dp(i - 1, steps - 1);
14
let moveRight = dp(i + 1, steps - 1);
15
let stay = dp(i, steps - 1);
16
return (memo[i][steps] = (moveLeft + moveRight + stay) % mod);
17
}
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0