java在递归函数中保留信息 [英] java retain information in recursive function
问题描述
是否可以通过java的辅助函数保留信息,而不使用静态变量。
Is it possible to retain information via a helper function with java, without using static variables.
例如,
public void foo(){
int v = 0;
fooHelper(2);
}
public void fooHelper(int depth){
v++;
fooHelper(depth-1)
}
即我想更新变量v不会丢失每个递归情况的信息,而不必访问函数外的变量。
Namely I want to update variable v without loosing the information for each recursive case, without having to access a variable outside the function.
推荐答案
忘记所有答案告诉你声明属性,或者在每次递归调用中更新可变对象。在一个真正的函数式递归样式中,你通过将它作为参数和/或返回类型传递来保留信息。
Forget about all the answers that tell you to declare attributes, or to update mutable objects in each recursive call. In a true functional, recursive style you "retain" information by passing it as parameters and/or return types.
让我用一个简单的例子来说明,让我们说你想要递归计算 int []
中元素的总和。这里, state (需要在递归调用之间保留的信息)是数组中的当前索引和到目前为止的总和。以下是如何做到这一点:
Let me illustrate with a simple example, let's say that you want to recursively calculate the sum of the elements in an int[]
. Here, the state (the information that needs to be retained between recursive calls) is the current index in the array and the sum so far. Here's how to do it:
public int sum(int[] array) {
return sum(array, 0, 0);
}
private int sum(int[] array, int idx, int acc) {
if (idx == array.length)
return acc;
return sum(array, idx+1, acc+array[idx]);
}
这样称呼:
int[] array = {1, 2, 3};
System.out.println(sum(array));
如您所见,无需声明(静态或实例)属性,也无需传递和修改可变对象(列表,映射) - 我甚至不使用局部变量,因为解决问题所需的所有必需信息都作为方法参数出现。
As you can see, there's no need to declare (static or instance) attributes, and no need to pass and modify mutable objects (lists, maps) - I'm not even using local variables, because all the required information needed to solve the problem is present as method parameters.
在您的问题中的代码中, v
变量应该执行 acc
参数在我的答案中所做的事情,即:每次调用递归时修改累加值。最后,你只需要从辅助函数(它不能有 void
返回类型)返回累计值,这就是你将如何得到 foo()
。
In the code in your question the v
variable is supposed to do what the acc
parameter is doing in my answer, namely: modifying an accumulated value each time the recursion is called. In the end, you just need to return the accumulated value from the helper function (which must not have a void
return type) and that's how you'll get the value in foo()
.
这篇关于java在递归函数中保留信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!