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 still at index 0
after exactlysteps
steps.
Since the answer may be too large, return it modulo 10^9 + 7
.
Example 1:
Example 2:
Constraints:
1 <= steps <= 500
1 <= arrLen <= 10^6
Tags
Dynamic Programming
Solution
We define dp[steps][idx]
as the number of ways to back to index 0 with exactly steps
moves. The number of rows is steps
, yet that of columns is min(arrLen, steps/2+1)
. If a pointer from index 0 wants to go back with steps
moves, it can only reach as far as index steps/2
. We initialize dp[0][*] = 1
. For each step i
from 1 to steps
, we have the transition function dp[i][j] = dp[i-1][j-1] + dp[i-1][j]+dp[i-1][j+1]
. Finally, we return dp[steps][0]
. We notice that the state of the current step is only related to its pervious step, thus, we can compress the 2D array into 1D with the length of min(arrLen, steps/2+1)
.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?