题目截图
题目分析
- 建立一个dict快速判断石头(不能直接数组,因为2**31)
- dfs记录curPos和lastJump 由此确定当前的步数,以及下一个的位置是不是石头
- 如果能去到stones[-1]即完成任务
- 记忆化一下即可
ac code
class Solution:
def canCross(self, stones: List[int]) -> bool:
target = stones[-1]
isStone = defaultdict(int)
for stone in stones:
isStone[stone] = 1
flag = False
@cache
def dfs(curPos, lastJump):
nonlocal flag
if curPos == target:
flag = True
return
if flag:
return
for thisJump in range(lastJump - 1, lastJump + 2):
if thisJump <= 0:
continue
if isStone[curPos + thisJump] == 1:
dfs(curPos + thisJump, thisJump)
dfs(0, 0)
return flag
总结
- 动态规划题两种思路
- 正向dp不好写的话 扔给 记忆化dfs