0

I was trying to solve Leetcode JumpGame using a recursive backtracking problem by the following method. It is wrong, but my answer is just one variable name different than the solution. I used "position" instead of "nextPosition" in the recursion. Can you help me with the reason?

My code:

class Solution {
    public boolean canJump(int[] nums) {
        int location=0;
        int end=nums.length-1;
        return backtrack(nums,location,end);
    
    }
    private boolean backtrack(int[] nums, int location, int end){
        //end condition
        if(location==end){
           return true;
        }
        //recursion 
        for(int i=1;i<=nums[location];i++){
            location=Math.min(location+i,end);  //jump! location updated
            if(backtrack(nums,location,end)){
                return true;
            }
        }
        return false;
    }
}

Solution:

public class Jumpgame55 {
    public boolean canJump(int[] nums) {
        int location = 0;
        int end = nums.length - 1;
        return backtrack(nums, location, end);

    }

    private boolean backtrack(int[] nums, int location, int end) {
        //end condition
        if (location == end) {
            return true;
        }
        //recursion
        for (int i = 1; i <= nums[location]; i++) {
            int nextlocation = Math.min(location + i, end);  //jump! location updated
            if (backtrack(nums, nextlocation, end)) {
                return true;
            }
        }
        return false;
    }
}
Krishna Majgaonkar
  • 1,532
  • 14
  • 25
  • 1
    Yes, during recursion backtracking you need your original location variable. since it is changed, your loop will also change and you won't get correct answer for Math.min(location+i,end); since your location variable changed. Hope this helps. – Ran94 Feb 17 '21 at 15:09
  • Wow! your comment is so great. I got it!!! Thanks a lot. – Thea Liu Feb 19 '21 at 21:47

0 Answers0