😀403 frog jump (记忆化搜索)
https://leetcode.com/problems/frog-jump/
class Solution {
Map<String, Boolean> map = new HashMap<>();
public boolean canCross(int[] stones) {
if (stones.length <= 1) return true;
if (stones[1] != 1) return false;
return dfs(stones, 1, 1);
}
private boolean dfs(int[] stones, int index, int steps) {
if (index == stones.length - 1) {
return true;
}
if (map.containsKey(index + " " + steps)) {
return map.get(index + " " + steps);
}
boolean flag = false;
for (int i = index + 1; i < stones.length; i++) {
int curSteps = stones[i] - stones[index];
if (steps == curSteps) {
flag = flag || dfs(stones, i, curSteps);
}
if (steps + 1 == curSteps) {
flag = flag || dfs(stones, i, curSteps);
}
if (steps - 1 == curSteps) {
flag = flag || dfs(stones, i, curSteps);
}
}
map.put(index + " " + steps, flag);
return flag;
}
}Last updated