在 Java 中的递归调用之间检索值
我有一个递归代码,可以在每次调用时从集合中删除值。当它从调用返回到上一个递归时,我希望该集合被补充为与进入调用之前完全相同的状态。例如,在下面的代码中:
// initial value of this list is [a,b,c]
void foo(ArrayList<Character> myList)
{
for(int i=0; i< size;i++)
{
myList.remove(i); // Now it becomes [b,c]
foo(myList);
/* QUESTION: at this point how do i retrieve the value [b,c] -- because it goes into successive recursive calls I'm unable to get this value back!!*/
}
}
I have a recursive code that removes values from the set at every call. When it returns from the call to the previous recursion, I want that set to be replenished with exactly the same state it had before going into the call. So for eg in the code below:
// initial value of this list is [a,b,c]
void foo(ArrayList<Character> myList)
{
for(int i=0; i< size;i++)
{
myList.remove(i); // Now it becomes [b,c]
foo(myList);
/* QUESTION: at this point how do i retrieve the value [b,c] -- because it goes into successive recursive calls I'm unable to get this value back!!*/
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在递归调用中将
myList
的副本传递给 foo:Pass a copy of
myList
to foo in the recursive call:一般来说,你不需要。
要保留某些内容,您需要在递归调用之前复制它:
In general, you don't.
To preserve something you'd need to make a copy of it before the recursive call:
这就是我递归地执行此操作的方式:
但是您似乎有兴趣在任何递归之前访问原始列表。因此,您将被迫保持原始参数列表不变,并将其与包含原始输入的计算或处理进度的另一个列表一起传递给每个递归。
这就是我使用它的方式,
如果我们遵循原始示例,我假设结果将始终是一个空列表。我只是在纸上完成了这一切,所以我没有在代码中对其进行测试。我希望这个想法足够清楚。
This is how I'd do it recursively:
But you seem to be interested in having access to the original list before any recursion. So you will be forced to keep the original parameter list unchanged and pass it as such to every recursion along with another list containing the progress in your calculations or processing over the original input.
This is how I'd use it
I assume the result will always be an empty list if we follow you original example. I did all this just in paper, so I have not tested it in code. By I hope the idea is clear enough.