[LeetCode] Number of Ways to Stay in the Same Place After Some Steps

1269. Number of Ways to Stay in the Same Place After Some Steps

You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).

Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
int dp[251][501];
int mod = 1e9 + 7;
int helper(int n, int i, int step) {
if(step == 0) return i == 0;
if(dp[i][step] != -1) return dp[i][step];
return dp[i][step] = ((helper(n, i, step - 1) + (i - 1 >= 0 ? helper(n, i - 1, step - 1) : 0)) % mod + (i + 1 < n ? helper(n, i + 1, step - 1) : 0)) % mod;
}
public:
int numWays(int steps, int arrLen) {
memset(dp,-1,sizeof(dp));
return helper(min(steps/2 + 1, arrLen), 0, steps);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/number-of-ways-to-stay-in-the-same-place-after-some-steps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.