目录
Leetcode跳跃游戏大礼包55.跳跃游戏45.跳跃游戏21306.跳跃游戏3
Leetcode跳跃游戏大礼包
55.跳跃游戏
class Solution {
public boolean canJump(int[] nums
) {
int maxposition
=0;
int end
=0;
for(int i
=0;i
<nums
.length
-1;i
++){
maxposition
=Math
.max(maxposition
,nums
[i
]+i
);
if(i
==end
){
end
=maxposition
;
}
}
if(end
>=nums
.length
-1){
return true;
}
return false;
}
}
45.跳跃游戏2
class Solution {
public int jump(int[] nums
) {
int maxposition
=0;
int end
=0;
int steps
=0;
for(int i
=0;i
<nums
.length
-1;i
++){
maxposition
=Math
.max(maxposition
,nums
[i
]+i
);
if(i
==end
){
end
=maxposition
;
steps
++;
}
}
return steps
;
}
}
1306.跳跃游戏3
class Solution {
public boolean canReach(int[] arr
, int start
) {
boolean[] visited
=new boolean[arr
.length
];
return dfs(start
,arr
,visited
);
}
public boolean dfs(int index
,int[] arr
,boolean[] visited
){
if(arr
[index
]==0){
return true;
}
visited
[index
]=true;
int left
=index
-arr
[index
];
if(left
>=0 && !visited
[left
] && dfs(left
,arr
,visited
)){
return true;
}
int right
=index
+arr
[index
];
if(right
<=arr
.length
-1 && !visited
[right
] && dfs(right
,arr
,visited
)){
return true;
}
return false;
}
}```
转载请注明原文地址:https://tech.qufami.com/read-24530.html