基于Java中的递归算法,我很难理解以下代码.我不明白,什么是不同的价值x,y并且当他们彼此呼唤时有什么?我试图通过System.out.print()在代码中调用来获得正确的值,但仍然没有得到帮助.
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我不是编程大师,我正在努力学习Java.任何帮助表示赞赏.
您引用的 x 和 y 值链接到数字金字塔中的特定数字。
您的算法所做的是通过添加顶部数字来找到金字塔的最大路径,然后将大金字塔分成两个较小的金字塔:
{7},
{2, 4},
{8 ,5, 9}
Run Code Online (Sandbox Code Playgroud)
和
{4},
{4, 6},
{5, 9, 3}
Run Code Online (Sandbox Code Playgroud)
。
然后,它对较小的金字塔执行相同的过程(我将仅对顶部金字塔执行此操作):
{2},
{8 ,5}
Run Code Online (Sandbox Code Playgroud)
和
{4},
{5, 9}
Run Code Online (Sandbox Code Playgroud)
。
现在您可以看到,当它分解这些金字塔时,只留下 2 个数字,因此它返回它们。当它爬回堆栈时,它会比较返回的值并返回较大的值。
最终,我们通过暴力检查金字塔中的每条线索到达了金字塔顶。
(顺便说一下,projecteuler.net上也有同样的问题)
| 归档时间: |
|
| 查看次数: |
2021 次 |
| 最近记录: |