理解Java中的递归 [英] Understanding Recursion in Java
问题描述
我很难理解基于Java中的递归算法的以下代码。我不明白,当他们互相打电话时, x
和 y
的价值是多少?我试图通过在代码中调用 System.out.print()
来获得正确的值,但仍然没有得到帮助。
I'm having a tough time in understanding the following code based on recursion algorithm in Java. I don't understand, what's the different value x
and y
have when they call within one another? I tried to get the right value by calling System.out.print()
within a code, but still get no help.
public class RecursionExample
{
private static int[][] arr={
{3},
{7, 4},
{2, 4, 6},
{8 ,5, 9, 3}
};
public static int maxSum(int[][] graph, int x, int y, int sum) {
if (x == 3)
{
return sum+graph[x][y];
}
int max= Math.max(maxSum(graph, x+1, y, sum), maxSum(graph, x+1, y+1, sum));
sum += graph[x][y];
return sum+max;
}
public static void main(String[] ar)
{
System.out.println(maxSum(arr,0,0,0));
}
}
我不是编程大师,我我想通过这样做来学习Java。任何帮助都表示赞赏。
I'm not a master in programming, and I'm trying to learn Java by doing. Any help is appreciated.
推荐答案
基本上,这会一直调用自己直到你到达第三次迭代( x == 3
)。
Essentially, this keeps calling itself until you reach the third iteration (x==3
).
所以,这是流量(减去对 maxSum $ c $的两次调用c>在
max
...为了简单起见)(每个缩进是对 maxSum
的调用):
So, here's the flow (minus the two calls to maxSum
within max
...for simplicity's sake) (each indent is a call to maxSum
):
x = 0
y = 0
sum = 0
x != 3
x = 1
y = 0
sum = 0
x != 3
x = 2
y = 0
sum = 0
x != 3
x = 3
y = 0
sum = 0
x == 3
return 0 + 8 //graph[3][0] == 8
max = 8 //previous return
sum = 0 + 2 //graph[2][0] == 2
return 10 //max + sum == 8 + 2 == 10
max = 10
sum = 0 + 7 //graph[1][0] == 7
return 17
max = 17
sum = 0 + 3 //graph[0][0] == 3
return 20
这篇关于理解Java中的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!