Intuition
Try every possible jump from each position recursively. If any path reaches the last index, return true.
Explanation
Brute Force
From the current position, try every jump length from 1 to nums[current]. Recursively check if any of those positions can reach the end.
This explores all possible paths, leading to O(2^n) time in the worst case because each position can branch into multiple sub-problems. Space is O(n) for the recursion stack.
Why it is slow: Many positions are revisited across different paths, and the exponential branching makes it impractical for large inputs.
Implementation
import java.util.*;
class Solution {
public boolean canJump(int[] nums) {
Boolean[] memo = new Boolean[nums.length];
return dfs(nums, 0, memo);
}
private boolean dfs(int[] nums, int i, Boolean[] memo) {
if (i >= nums.length - 1) return true;
if (memo[i] != null) return memo[i];
for (int jump = 1; jump <= nums[i]; jump++) {
if (dfs(nums, i + jump, memo)) {
memo[i] = true;
return true;
}
}
memo[i] = false;
return false;
}
}