1269. Number of Ways to Stay in the Same Place After Some Steps
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 <= 500
1 <= 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 \geq 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 \times steps)$, and the space complexity is $O(steps \times steps)$. Where $steps$ is the number of steps given in the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|