Search code examples
pythonalgorithmrecursionnested-loops

Leetcode jumpgame recursive approach


Given the following problem:

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]

Output: True

Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]

Output: False

Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

I am trying to come up with a recursive solution. This is what I have so far. I am not looking for the optimal solution. I am just trying to solve using recursion for now. If n[i] is 0 I want the loop to go back to the previous loop and continue recursing, but I can't figure out how to do it.

def jumpGame(self, n: []) -> bool:
    if len(n) < 2:
        return True
    for i in range(len(n)):                      
        for j in range(1, n[i]+1):
            next = i + j
            return self.jumpGame(n[next:])
    return False

Solution

  • If you want to do recursively and you said no need to be optimal ( so not memoized ), you could go with the below method. You don't need nested loops. Also no need to explore all paths, you could optimize by looking at the step that you are going by checking i + (jump) < n

    def jumpGame(a, i):
      if i > len(a) - 1:
        return False
      if i == len(a) - 1:
        return True
      reached = False
      for j in range(1, a[i] + 1):
        if i + j < len(a):
          reached = jumpGame(a, i + j)
        if reached:
          return True
      return reached
    
    print(jumpGame([2, 3, 1, 1, 4], 0))
    print(jumpGame([3,2,1,0,4], 0))
    
    True
    False