-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path403. Frog Jump.cpp
39 lines (29 loc) · 1.08 KB
/
403. Frog Jump.cpp
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
31
32
33
34
35
36
37
38
39
class Solution {
boolean[][] dp;
public boolean canCross(int[] stones) {
if(stones[1]!=1) return false;
int n = stones.length;
dp = new boolean[n][n];
return helper(stones,0,1);
}
boolean helper(int[] stones,int lastIndex,int currentIndex){
if(currentIndex == stones.length - 1){
return true;
}
if(dp[lastIndex][currentIndex]) return false;
int lastJump = stones[currentIndex] - stones[lastIndex];
int nextIndex = currentIndex + 1;
while(nextIndex<stones.length && stones[nextIndex]<= stones[currentIndex] + lastJump + 1){
int nextJump = stones[nextIndex] - stones[currentIndex];
int jump = nextJump - lastJump;
if(jump>=-1 && jump<=1){
if(helper(stones,currentIndex,nextIndex)){
return true;
}
}
nextIndex++;
}
dp[lastIndex][currentIndex] = true;
return false;
}
}