Recursion (Brute Force)
Intuition
From each position, try every possible jump length from 1 to nums[i] and recursively check if any of those jumps eventually leads to the last index. This explores all possible jump sequences, resulting in exponential time because many positions are revisited from different paths.
Algorithm
- Start at index `0`.
- If the current index is the last index, return `true`.
- For each jump length `j` from 1 to `nums[i]`, recursively check if `index + j` can reach the end.
- If any jump succeeds, return `true`; otherwise, return `false`.
O(2^n)SpaceO(n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
bool canJump(vector<int>& nums) {
return helper(nums, 0);
}
bool helper(vector<int>& nums, int pos) {
if (pos == (int)nums.size() - 1) return true;
int maxJump = min((int)nums.size() - 1, pos + nums[pos]);
for (int next = pos + 1; next <= maxJump; next++) {
if (helper(nums, next)) return true;
}
return false;
}
};class Solution {
public boolean canJump(int[] nums) {
return helper(nums, 0);
}
private boolean helper(int[] nums, int pos) {
if (pos == nums.length - 1) return true;
int maxJump = Math.min(nums.length - 1, pos + nums[pos]);
for (int next = pos + 1; next <= maxJump; next++) {
if (helper(nums, next)) return true;
}
return false;
}
}from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
def helper(pos: int) -> bool:
if pos == len(nums) - 1:
return True
max_jump = min(len(nums) - 1, pos + nums[pos])
for next_pos in range(pos + 1, max_jump + 1):
if helper(next_pos):
return True
return False
return helper(0)func canJump(nums []int) bool {
var helper func(pos int) bool
helper = func(pos int) bool {
if pos == len(nums)-1 {
return true
}
maxJump := pos + nums[pos]
if maxJump > len(nums)-1 {
maxJump = len(nums) - 1
}
for next := pos + 1; next <= maxJump; next++ {
if helper(next) {
return true
}
}
return false
}
return helper(0)
}