Description
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 exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
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:
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
Example 3:
Input: steps = 4, arrLen = 2 Output: 8
Constraints:
1 <= steps <= 5001 <= arrLen <= 106
Solutions
Solution 1: Memoization Search
We observe the data range of the problem and find that steps does not exceed 500, which means that we can only go to the right for up to 500 steps.
We can design a function dfs(i, j), which represents the number of schemes when we are currently at position i and the remaining steps are j. So the answer is dfs(0, steps).
The execution process of the function dfs(i, j) is as follows:
- If i \gt j or i ≥ arrLen or i \lt 0 or j \lt 0, then return 0.
- If i = 0 and j = 0, then the pointer has stopped in place and there are no remaining steps, so return 1.
- Otherwise, we can choose to move one step to the left, one step to the right, or stay still, so return dfs(i - 1, j - 1) + dfs(i + 1, j - 1) + dfs(i, j - 1). Note the modulo operation of the answer.
During the process, we can use memoization search to avoid repeated calculations.
The time complexity is O(steps × steps), and the space complexity is O(steps × steps). Where steps is the number of steps given in the problem.
class Solution: def numWays(self, steps: int, arrLen: int) -> int: @cache def dfs(i, j): if i > j or i >= arrLen or i < 0 or j < 0: return 0 if i == 0 and j == 0: return 1 ans = 0 for k in range(-1, 2): ans += dfs(i + k, j - 1) ans %= mod return ans mod = 10**9 + 7 return dfs(0, steps)(code-box)
