【问题标题】:Recursive method and stack overflow递归方法和堆栈溢出
【发布时间】:2013-10-17 05:32:49
【问题描述】:

好的,所以我有一个任务来确定一只猴子爬 x 高度的杆子需要多长时间。如果在 10 分钟内上升 10 英尺,在休息时在 10 分钟内滑落 3 英尺。当它到达杆子的顶部时,它会停下来,并以每分钟一英尺的速度爬升。这使用递归,到目前为止我的方法是正确的,但是我遇到了堆栈溢出,我不知道如何避免它,所以我吓坏了,知道吗?

谢谢大家

public static long climb(long height, long time) {    //Recursive method

    if (height <= 0)     //base case
        return time;

/*Every 10 min add 3 to height (notice im doing it backwards, 
instead of substracting 3.
I find it easier to deal with this way and easier to implement the base case) *//

    else if (time != 0 && time % 10 == 0) {    

        return climb(height+3, time+10);
    }

    else  {
        return climb(height-1, time+1);

    } } }

【问题讨论】:

  • 好吧,如果你在 time 是 10(或零)的任意倍数的情况下调用该方法,它会不断调用 climb(height+3, time+10); 方法,你会用完堆栈。即,您的递归不起作用。
  • 高度和时间的初始值是多少。

标签: java recursion


【解决方案1】:

你不能那样做。这两行可能有问题:

else if (time != 0 && time % 10 == 0) {    

    return climb(height+3, time+10);
}

如果您遇到时间为 10 的情况,则将 10 添加到 time-var 并最终为 20,因此 20 % 10 将再次返回 true :)

编辑:\

该死的,有点太晚了:)

另一个编辑:\

为避免此问题,请在参数中添加提醒:

    public static long Climb(long height, long time, bool justrested)
    {
        //Recursive method
        if (height <= 0)
        {
            //base case
            return time;
        }

        if(time%10 == 0 && !justrested)
        {
            return Climb(height + 3, time + 10, true);
        }

        return Climb(height - 1, time + 1, false);
    }

你现在可以这样调用它:

Climb(1800, 0, true);

可能有一些错误,但无论如何希望是你。

【讨论】:

  • OHHHH 这确实有效!非常感谢你!我非常感谢! :)
【解决方案2】:

Stack内存满时报错,即这里的问题 是您没有有效的退出语句。

尝试将其更改为长

if (height <= 0L) 

它可能会解决问题。

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 2017-08-26
    • 2016-11-09
    • 2020-07-13
    • 2017-01-20
    • 2018-12-02
    • 2017-09-06
    • 2019-07-08
    • 2015-08-05
    相关资源
    最近更新 更多