本文介绍了在Java中好一点的了解递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我真搞不清楚一些有关递归在Java中。说我有以下code:

Ok I'm really confused about something about recursion in Java. Say I have the following code:

static int findShortestString(String[] paths, int lo, int hi) {
        if(lo==hi)
            return lo;
        int minindex=findShortestString(paths,lo+1, hi);
        if(safeStringLength(paths[lo])<safeStringLength(paths[minindex]))
            return lo;
        return minindex;

现在的问题是不是真的对code本身,而只是递归是如何工作的。 minindex被设定为等于一个递归调用。所以第一次函数运行并试图设置minindex的东西,它这样做,然后将该函数调用自身。但是,当确实if语句运行呢?它会只有当minindex最后居然拥有真正的价值运行?我只是不能环绕此我的头。如果minindex导致函数递归和递归,那么当将if语句不断进行检查?当罗==喜?我不明白:(

Now the question is not really about the code itself, but just about how recursion works. minindex is being set equal to a recursive call. So the first time the function run and tries to set minindex to something, it does so, and then the function calls itself. But when does the if statement run then? Will it only run when minindex finally actually holds a real value? I just cant wrap my head around this. If minindex causes the function to recurse and recurse, then when will the if statement ever be checked? When lo==hi? I dont get it:(

推荐答案

minindex 未分配,直到 findShortestString 返回的,这将不会发生,直到罗==喜

minindex is not assigned until findShortestString returns, which won't happen until lo == hi.

每次方法调用本身,它缩小了罗之间的差异 1,所以最终他们会是平等*和该值将被退回。

Each time the method calls itself, it narrows the difference between lo and hi by 1, so eventually they'll be equal* and that value will be returned.

这是例如,路径= [P1,PATH2,longpath3]


lo = 0, hi = 2
lo != hi -> call findShortestString(paths, 1, 2)

  lo = 1, hi = 2
  lo != hi -> call findShortestString(paths, 2, 2)

    lo = 2, hi = 2
    lo == hi -> return lo (=2)

  lo = 1, hi = 2, minindex = 2
  length of "path2" < length of "longpath3" -> return lo (= 1)

lo = 0, hi = 2, minindex = 1
length of "p1" < length of "path2" -> return lo (= 0)

我试图说明变量的值在递归的使用越来越多的缩进的每个级别。在每次递归调用的开始,和的previous值 minindex 保存关闭(在一个被称为栈结构),并用来代替新值。当该方法的返回的每次调用,previously保存的值弹出从堆栈中使用,而 minindex 从分配previous返回值。

I've tried to illustrate the variable values at each level of recursion using increasing amounts of indentation. At the beginning of each recursive call, the previous values of lo, hi and minindex are saved off (in a structure called a "stack") and the new values used instead. When each invocation of the method returns, the previously saved values are "popped" off the stack for use, and minindex assigned from the previous return value.

*除非LO&GT;您好,首先,我想...

*unless lo > hi to begin with, I guess...

这篇关于在Java中好一点的了解递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 23:59