简体   繁体   English

递归在这里如何工作?

[英]How does recursion work here?

Recursion is a new practice for me and I am trying to get better at it and understand how the methods return. 递归对我来说是一种新的实践,我正在尝试做得更好,并了解方法如何返回。 I have the following program but am unfailiar with how to use the this keyword. 我有以下程序,但对如何使用this关键字不满意。 Can you please review the code and walk me through the program showing the values held by the variables as the methods execute? 您能否查看一下代码,并逐步引导我完成显示方法执行时变量所包含的值的程序?

I have tried numerous things to determine how the value answer in the compute method holds 14 after execution can anyone walk me through the first few recursive calls so I can try and figure out the rest? 我已经尝试了很多方法来确定执行后,compute方法中的值答案如何保持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 = this.go(stuff, 0);
        System.out.println("The answer is " + answer);

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

}

Ok so a few things I notice here: 好了,我在这里注意到以下几点:

The purpose of go() seems to be calculating the sum of the numbers in the array. go()的目的似乎是计算数组中数字的总和。 If this is the case, your method should look like this: 在这种情况下,您的方法应如下所示:

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

This is because numbers.length in this case will return 4, but the last element in this array is at index 3 (arrays are 0-indexed). 这是因为在这种情况下,numbers.length将返回4,但是此数组中的最后一个元素在索引3处(数组的索引为0)。

This way, when the function is called with the second parameter set to 3, it will return the value of the last element in the array and then the code will "bubble up" (as I like to call it) and calculate the sum of the elements by subsequently returning the current summed value + the value of the current call. 这样,在第二个参数设置为3的情况下调用该函数时,它将返回数组中最后一个元素的值,然后代码将“冒泡”(就像我喜欢的那样)并计算通过随后返回当前求和值+当前调用的值来表示元素。

As for your problem with the this keyword, it's actually very simple. 至于使用this关键字的问题,实际上非常简单。 this always refers to the current class instance your code is in. In this case, you create a Recurs1 instance called r in your main function so whenever you call a method on that particular object, the this keyword used in those methods will refer to r . this始终引用您代码所在的当前类实例。在这种情况下,您在主函数中创建一个名为rRecurs1实例,因此,每当对该特定对象调用方法时,这些方法中使用的this关键字将引用r If you created multiple Recurs1 objects (each with potential different internal states) in your program, their respective this references would always point to themselves allowing you to access their member variables and methods. 如果在程序中创建了多个Recurs1对象(每个Recurs1对象具有可能不同的内部状态),则它们各自的this引用将始终指向自身,从而允许您访问其成员变量和方法。

Hope that helps and good luck, recursion is usually what most people have trouble getting their heads around at first but once you get used to it it's pretty cool! 希望对您有所帮助,并祝您好运,通常大多数人一开始都会遇到递归问题,但是一旦习惯了,那就很酷了!

OK so this is not an answer to your question per se, more like a lesson in recursion. 好的,所以这本身不是您问题的答案,更像是递归课程。

Keep in mind I have never tried to to do this with a java class. 请记住,我从未尝试使用Java类来做到这一点。

Recursion means a function that calls itself repeatedly until a answer has been reached, or your function detects you are running out of stack space. 递归表示函数重复调用自己,直到获得答案为止,或者函数检测到堆栈空间不足。

You first step into the function determines if you will call yourself. 您首先要进入该函数,以确定是否可以自称。

When you call yourself you will push a new copy of the data onto the stack and begin executing. 当您自称时,您会将数据的新副本推入堆栈并开始执行。 I think in the case of java you will allocate a new object into the heap ( don't quote me on this ) and each invocation will have a new set of variables that get populated with new values. 认为在Java的情况下,您将在堆中分配一个新对象(对此不加引号),并且每次调用都将具有一组新的变量,这些变量将填充新的值。

As you recurse deeper and deeper you simply allocate new copies of the object until you find the answer or run out of memory. 随着递归的深入,您只需分配对象的新副本,直到找到答案或内存不足。

If you find the answer you then return the result to the previous level in the stack of objects eg: 如果找到答案,则将结果返回到对象堆栈中的上一级,例如:

int foo(int i ){
  if(some condition){ 
   return foo(i);
  } else
   return i  
}

as You can see if the condition tests true the foo() keeps getting called. 如您所见,如果条件测试为true,则foo()不断被调用。 Now at each call, the variables of foo() are saved for as many levels deep as you go. 现在,在每次调用时,foo()的变量都会保存到您可以访问的多个级别。 If the condition tests false then each instance of foo() returns to the previous until you are at the original invocation of foo() which then returns to the caller of foo(). 如果条件测试为false,则foo()的每个实例都会返回到前一个实例,直到您对foo()进行了原始调用,然后才将其返回给foo()的调用者。

Clear as Mud? 像泥一样清除?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM