public class Solution {
// state: f[i] = is ith element reachable
// function: f[i] = OR(f[j], i - j <= nums[j])
// initialize: f[0] = true
// result = f[nums.length]
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
boolean[] f = new boolean[nums.length];
f[0] = true;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (f[j] && j + nums[j] >= i) {
f[i] = true;
break;
}
}
}
return f[nums.length - 1];
}
}
Greedy, time complexity: O(n)
public class Solution {
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
int reachable = nums[0];
for (int i = 0; i <= reachable && i < nums.length; i++) {
reachable = Math.max(reachable, i + nums[i]);
}
return reachable >= nums.length - 1;
}
}
没有评论:
发表评论