题目链接
代码参考自
public static boolean flag = false;
// 用来判断当前走过来距离是否有这样一个数
public int judge(int []stones, int value) {
int left = 0, right = stones.length - 1, mid = 0;
while (left <= right) {
mid = (left + right) >> 1;
if (stones[mid] > value) {
right = mid - 1;
} else if (stones[mid] < value) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
// 当前下标,走过来的k值,数组
public void dfs(int index, int k, HashMap<Integer, HashSet<Integer>> mp, int []stones) {
if (index >= stones.length - 1 || flag) {
flag = true;
return;
}
// 减枝操作,如果之前有通过k值走过来,那么没有必要接着往下走了
// 并且stones[index] + k 在数组有这个值
int temp = judge(stones, k + stones[index]);
if (!mp.get(index).contains(k) && temp > -1) {
mp.get(index).add(k);
dfs(temp, k - 1, mp, stones);
dfs(temp, k, mp, stones);
dfs(temp, k + 1, mp, stones);
}
}
public boolean canCross(int[] stones) {
if (stones == null || stones.length < 2) {
return false;
}
flag = false;
HashMap<Integer, HashSet<Integer>> mp = new HashMap<>();
for (int i = 0; i < stones.length; i++) {
mp.put(i, new HashSet<>());
}
dfs(0, 1, mp, stones);
return flag;
}