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 is still at index 0 after exactlysteps steps. Since the answer may be too large, return it modulo10^9 + 7.
Input:
steps = 3, arrLen = 2
Output:
4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
1
2
3
4
5
6
7
Input:
steps = 2, arrLen = 4
Output:
2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
classSolution {
publicintnumWays(int steps, int arrLen) {
int MOD = 1_000_000_007, maxPos = Math.min(arrLen, steps+1);
int[][] dp =newint[steps+1][maxPos];
dp[0][0]= 1;
for (int s = 1; s <= steps; ++s) {
for (int i = 0; i < maxPos; ++i) {
dp[s][i]= dp[s-1][i];
if (i > 0) dp[s][i]= (dp[s][i]+ dp[s-1][i-1]) % MOD;
if (i+1 < maxPos) dp[s][i]= (dp[s][i]+ dp[s-1][i+1]) % MOD;
}
}
return dp[steps][0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funnumWays(steps: Int, arrLen: Int): Int {
val MOD = 1_000_000_007
val maxPos = minOf(arrLen, steps+1)
val dp = Array(steps+1) { IntArray(maxPos) }
dp[0][0] = 1for (s in1..steps) {
for (i in0 until maxPos) {
dp[s][i] = dp[s-1][i]
if (i > 0) dp[s][i] = (dp[s][i] + dp[s-1][i-1]) % MOD
if (i+1 < maxPos) dp[s][i] = (dp[s][i] + dp[s-1][i+1]) % MOD
}
}
return dp[steps][0]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defnumWays(self, steps: int, arrLen: int) -> int:
MOD =10**9+7 maxPos = min(arrLen, steps+1)
dp = [[0]*maxPos for _ in range(steps+1)]
dp[0][0] =1for s in range(1, steps+1):
for i in range(maxPos):
dp[s][i] = dp[s-1][i]
if i >0:
dp[s][i] = (dp[s][i] + dp[s-1][i-1]) % MOD
if i+1< maxPos:
dp[s][i] = (dp[s][i] + dp[s-1][i+1]) % MOD
return dp[steps][0]