在使用递归二维数组之和的整数? [英] Sum integers in 2d array using recursion?
问题描述
我需要一些帮助这个问题。我来总结所有整数使用递归二维数组。下面是我已经成功地对我自己做的,但我坚持。这code产生的总和14,这应该是18。
I need some help with this problem. I have to sum all integers in a 2d array using recursion. Below is what I have managed to do on my own, but I'm stuck. This code generates the sum 14, which should be 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);
}
}
有什么建议?是基础的情况下错了吗?或者是递归的方法错了?
Any suggestions? Is the base case wrong? Or is the recursive method wrong?
推荐答案
我想用两个函数解决这个问题。首先创建一个可以递归总结单(1D)阵列的功能。在编写递归总结外阵列超过previous功能的功能。
I would solve this using two functions. First create a function that can recursively sum a single (1d) array. The write a function that recursively sums the previous function over the outer array.
记住表[N]是本身的阵列。您没有访问所有一气呵成。
Remember that table[N] is itself an array. You don't have to access it all in one go.
这篇关于在使用递归二维数组之和的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!