Loading...

10-15 leetcode 1269

链接 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 is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.

题解

这题一看就是个 dp,直接可以分为三种情况讨论

  1. 保持原地不动
  2. 步数+1,是从左侧来的
  3. 步数+1,是从右侧来的

然后这里需要处理一点是需要取步数和数组长度的最小值,避免越界

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def __init__(self):
self.mod = (10**9) + 7

def numWays(self, steps: int, arrLen: int) -> int:
max_index = min(steps, arrLen - 1)
dp = [[0] * (max_index + 1) for _ in range(steps + 1)]
dp[0][0] = 1
for i in range(1, steps + 1):
for j in range(max_index + 1):
dp[i][j] = dp[i - 1][j]
if j - 1 >= 0:
dp[i][j] += dp[i - 1][j - 1]
if j + 1 <= max_index:
dp[i][j] += dp[i - 1][j + 1]
return dp[steps][0] % self.mod

Comment