0

Is there a way to use recursion to populate arrays, without implementing method overloading? I want to build a method that takes only an int as argument, and returns an array. The only solution I have thought of is using method overloading; the function that takes int as argument builds the array and passes both the array and the int to the second function, which takes both the int and the array as arguments and implements the actual recursion.

Here is an example:

public static int[] recursiveBuilder(int depth, int[] anArray){
    // Base case:
    if (depth < 0){
        return anArray;
    }
    // Recursion:
    else{
        anArray[depth] = depth;
        depth--;
        return recursiveBuilder(depth, anArray);
    }
}

public static int[] recursiveBuilder(int depth){
    return recursiveBuilder(depth, new int[depth + 1]);
}

If I declare the array in the recursive part of the overloading, the array would get initialized every time the recursion is called, so I used a second function to declare the array.

Is this approach considered good? Efficient? Is there a way to implement this dynamic in only one method?

4

1 回答 1

1

很常见的是,递归解决方案需要两种方法。使用外部有意义的参数调用顶部方法,执行任何所需的设置,并调用递归方法。递归方法需要额外的参数。

例如,递归二分搜索可能有一个 top 方法,该方法仅将探针和对数组的引用作为参数。递归方法还需要一个开始和结束索引,因此它可以将自己限制在数组的一个切片中。

Java 程序通常有很多小方法,Java 实现就是为了处理这些而设计的。如果您可以使您的代码清晰并使用两种方法,请使用两种方法并继续下一步。

于 2013-09-02T02:18:35.727 回答