递归中的跳跃游戏 [英] Jump Game in recursion

查看:59
本文介绍了递归中的跳跃游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试我理解递归的能力,所以我给自己分配了一个任务,在递归中进行跳跃游戏练习

I am trying to test my abilities to understand well the recursion so I gave myself the task to do the Jump Game exercice in recursion

给定一个非负整数数组,你最初被定位在数组的第一个索引处.数组中的每个元素代表你在那个位置的最大跳跃长度.你的目标是到达最后一个索引处最小跳跃次数.

https://leetcode.com/problems/jump-game-ii/

我尝试过这部分代码,但它没有出现在调试器上,所以我没有真正看到这个问题

I tried to to this part of code but It does not appear on the debugger so I am not really seeing the problem in this

def function(array, index, counter):
    if index >= len(array):
        return counter
    min_step = float('inf')
    for i in range(1, array[index]):
        min_step = min(min_step, function(array, index + i, counter + 1))

    return min(min_step, function(array[1:], index, counter))

如果有人能判断我的想法是否正确

If someone can tell if I am in the right direction of thinking

谢谢:)

推荐答案

你的功能很不错,只是修复了几个:

Your function is pretty good, just a few fixes:

  1. 您想要获得最后一个索引,即 len(array) - 1,而不是 len(array).
  2. 您希望跳转到并包括当前数组值的距离,因此您需要 range(1, array[index] + 1) 代替range(1, array[index]).
  3. min_step 已经包含最少数量的跳转.我不确定你想返回什么,但你可以return min_step.
  1. You want to get to the last index, which is len(array) - 1, not len(array).
  2. You want to enable jumps to a distance of up to and including the current array value, so you need range(1, array[index] + 1) instead of range(1, array[index]).
  3. min_step already contains the least amount of jumps. I'm not sure what you're trying to return but you can just return min_step.

考虑到这一点:

def function(array, index, counter):
    if index >= len(array) - 1:
        return counter
    min_step = float('inf')
    for i in range(1, array[index] + 1):
        min_step = min(min_step, function(array, index + i, counter + 1))

    return min_step

这篇关于递归中的跳跃游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆