LeetCode 1306
Jump Game 系列三:这个题目思路比较简单,那就是每次把两种情况都尝试一下,使用dfs+backtracking的方法,然后使用memo来记录一下之前已经访问过的点。一旦陷入循环,就可以认为不能到达0.
def canReach(self, arr: List[int], start: int) -> bool:
visited = set()
def dfs(arr:List[int], current: int, visited:set):
if current < 0 or current >= len(arr): return False
if arr[current] == 0: return True
if current in visited: return False
visited.add(current)
pre = current - arr[current]
after = current + arr[current]
if dfs(arr, pre, visited) or dfs(arr, after, visited):
return True
return False
return dfs(arr, start, visited)