【发布时间】:2011-04-10 23:23:28
【问题描述】:
我需要一些帮助来解决这个问题。我必须使用递归对二维数组中的所有整数求和。以下是我自己设法做的事情,但我被困住了。此代码生成总和 14,应该是 18。
public class tablerecursion {
public static void main(String[] args) {
int[][] tabell = new int[][] { { 1, 2, 3 }, { 3, 2, 1 }, { 1, 2, 3 } };
int sum = rec(tabell, 2, 2);
System.out.println(sum);
}
static int rec(int[][] table, int n, int m) {
if (m == 0)
return table[n][0];
if (n == 0)
return table[0][m];
System.out.println("n:" + n + " m:" + m);
return rec(table, n - 1, m) + rec(table, n, m - 1);
}
}
有什么建议吗?基本情况是错误的吗?还是递归方法不对?
【问题讨论】:
标签: java arrays recursion multidimensional-array