从递归方法返回

时间:2011-11-07 19:34:59

标签: java

我正在努力练习理解递归但是下面的程序让我难过。如何将答案返回14?有人能告诉我这是怎么计算的吗?我试图输入一些打印声明,以帮助我识别发生了什么,但我看不到斑点在上升到4之后是如何减少的。我有程序并输出到控制台下面,请帮助。

来自控制台:

The spot 1 is 0
The spot 1 is 1
The spot 1 is 2
The spot 1 is 3
The spot 1 is 4
when spot = length. the spot is 4
 The value is 4
spot after return 3
 the spot 2 is 3
 The value is 8
spot after return 2
 the spot 2 is 2
 The value is 11
spot after return 1
 the spot 2 is 1
 The value is 13
spot after return 0
 the spot 2 is 0
The answer is 14

代码:

public class Recurs1 {
    public static void main (String [] arg) {
        Recurs1 r = new Recurs1();
        r.compute();
    }

    public void compute() {
        int [] stuff = {1, 2, 3, 4};
        int answer = go(stuff, 0);
        System.out.println("The answer is " + answer);  
    }

    private int go(int[] numbers, int spot) {
        System.out.println("The spot 1 is " + spot);
      //System.out.println("0 is " + numbers[0] + " 1 is " + numbers[1] + " 2 is "  + numbers[2] + " 1 is " + numbers[3]);
        if (numbers.length == spot) {
            System.out.println("when spot = length. the spot is " + spot); return spot;     
            }
        int value = go(numbers, spot + 1 ); 
        System.out.println(" The value is " + value); 
        System.out.println("spot after return " + spot);
        System.out.println(" the spot 2 is " + spot);
        return value + numbers[spot]; 
     }

} 

3 个答案:

答案 0 :(得分:2)

当你到达终点时,尝试返回0而不是现场。你将4(当前的现货价值)加到最后。

答案 1 :(得分:0)

如果您的目标是编写一个对数组求和的方法,那么问题就是在go()行上你有if(numbers.length == spot)你返回的spot,即4,并且它将它添加到总值(因为调用go(数字,4)的方法是设置值并添加它。)相反,你应该返回0来停止递归(因为结果将是1 + 2 + 3 + 4 + 0)

尝试使用此尺寸:

private int go(int[] numbers, int spot){
    if(numbers.length == spot) return 0;
    return go(numbers, spot+1) + numbers[spot];
}

答案 2 :(得分:0)

也许我可以帮助您完成它。你的程序一直工作,直到它调用go(数字,3 + 1),返回4,因为数字有4个元素,而spot的值为4(3 + 1)。

此时您正在查看类似这样的调用堆栈:

answer = go(stuff, 0);
    value = go(numbers, 0 + 1);
        value = go(numbers, 1 + 1);
            value = go(numbers, 2 + 1);
                value = go(numbers, 3 + 1) = 4

现在它可以恢复堆栈。

go(numbers, 2 + 1 );

调用它会给你值+数字[3],即4 + 4,其值来自go(数字,3 + 1)。

接下来我们有

go(numbers, 1 + 1 );

这将返回go(数字,2 + 1)+数字[2],即8 + 3(或11)。

然后调用go(数字,0 + 1),返回go(数字,1 + 1)+数字[1],即11 + 2或13。

最后,可以计算go(stuff,0)。这将返回go(数字,0 + 1)+数字[0],即13 + 1或14 - 您当前得到的答案。

我不确定我是否真的解释过多,但希望通过它可以显示你的困惑在哪里。

另一种可视化的方式是这样的:

answer = go(stuff, 0);
    go(stuff, 0) = go(numbers, 0 + 1) + 1;
        go(numbers, 0 + 1) = go(numbers, 1 + 1) + 2;
            go(numbers, 1 + 1) = go(numbers, 2 + 1) + 3;
                go(numbers, 2 + 1) = go(numbers, 3 + 1) + 4;
                    go(numbers, 3 + 1) = 4;