1. Recursive Backtracking
Intuition
Recursively try every jump length from 1 to nums[pos] from the current position until the destination is reached or all paths fail.
Algorithm
- Step 1: If current position >= n - 1, return true.
- Step 2: Try every jump length from 1 up to nums[pos].
- Step 3: If any recursive call from pos + jump returns true, propagate true up.
- Step 4: If all jump choices fail, return false.
#include <iostream>#include <vector> using namespace std; class Solution { bool canJumpFrom(int pos, const vector<int>& nums) { if (pos >= (int)nums.size() - 1) return true; int furthest = min(pos + nums[pos], (int)nums.size() - 1); for (int next = pos + 1; next <= furthest; ++next) { if (canJumpFrom(next, nums)) return true; } return false; }public: bool canJump(vector<int>& nums) { return canJumpFrom(0, nums); }}; int main() { Solution sol; vector<int> nums1 = {2, 3, 1, 1, 4}; vector<int> nums2 = {3, 2, 1, 0, 4}; cout << boolalpha; cout << "nums1 reachable: " << sol.canJump(nums1) << endl; cout << "nums2 reachable: " << sol.canJump(nums2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)