法1: 记忆化搜索
简而言之 就是把已经搜索的值记录到一个hash表 如果已经搜索过 那么就不用继续往下搜索了
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 30
| MOD = 10 ** 9 + 7
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: memo = defaultdict(int) @cache def dfs(cur: int, d: int) -> int: if k - d < abs(endPos - cur): return 0 if d == k: return 1 key = cur * 1005 + d if memo.get(key): return memo[key] v = (dfs(cur + 1, d + 1) + dfs(cur - 1, d + 1)) % MOD memo[key] = v return v
return dfs(startPos, 0)
|
个人觉得记忆化写起来并没有dp方便 简洁性和正确性上来看 主要是记忆化需要判断较多的边界条件 能用dp的 还是尽量先考虑dp
法2:动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| MOD = 10 ** 9 + 7
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: if abs(endPos - startPos) > k: return 0
dp = [[0 for i in range(1010)] for _ in range(3010)] startPos = startPos + 1000 endPos = endPos + 1000 dp[startPos][0] = 1 for j in range(1,k+1): for i in range(startPos - k,endPos + k+1): dp[i][j] = (dp[i-1][j-1] + dp[i+1][j-1]) % MOD return dp[endPos][k]
|