【问题标题】:Java - Recursive Method that takes Cumulative sum in one array and returns anotherJava - 在一个数组中获取累积和并返回另一个数组的递归方法
【发布时间】:2014-03-04 03:53:21
【问题描述】:

所以问题来了:创建一个 int [] 递归方法,计算数组中的累积总和,并通过将数组中前面的值的总和添加到该值来转换数组中的每个值。例如,如果

数字 = [5, 6, 7, 2, 3, 1], 那么

结果 = [5, (5)+6, (5+6)+7, (5+6+7)+2, (5+6+7+2)+3, (5+6+7 +2+3)+1],

即,结果 = [5, 11, 18, 20, 23, 24]。

注意事项是:不能使用静态或 void 方法,不能使用循环。 到目前为止,这是我的代码:

    public int[] computeCumulativeSums(int[] numbers){

    if(numbers.length == 0)
    {
        return numbers; // Base case
    }
    else
    {
        //recursive stage not implemented. Don't know how to implement
        return numbers; 
    }

}
//Helper method
public int [] addNumbers(int [] list, int index)
{
    if(index == 0)
    {
        return list; //Helper method base case
    }
    else
    {
                    //recursive case
        return addNumbers(list, index - 1);
    }
}

public boolean searchTable(int[][] data, int element){
    return true;
}


public static void main(String [] args){

    Recursion r = new Recursion();
        int[] numbers = new int[] {5, 6, 7, 2, 3, 1};
    System.out.println(Arrays.toString(r.computeCumulativeSums(numbers)));  
}

输出:[5, 6, 7, 2, 3, 1]

我要问的是朝着正确的方向前进,因为我对此非常迷茫。您的帮助将不胜感激。

【问题讨论】:

    标签: java arrays recursion


    【解决方案1】:

    我的建议是:尝试使用 while 循环来完成。条件。在 while 循环中是您的停止条件。现在尝试将 while 循环中的内容转换为递归方法(或者,如果不能,则只是一个方法,然后查看每个方法如何执行方法本身的以下调用)。对你有帮助吗?

    【讨论】:

    • 不能使用任何循环。仅递归。
    • 我在谈论找出复发是什么的过程,复发。 while 循环可以系统地转换为循环。我只是想给出一个提示,但似乎现在已经发布了解决方案;)
    【解决方案2】:

    陈述你的策略..然后编写递归函数。你可能会有类似的东西:

    function summit(array, i) ... 
        if i > 0, then set array[i]=array[i-1]+array[i]
        if i < array.length the call summit(array,i+1)
        return
    

    【讨论】:

    • 感谢您的建议。我喜欢你没有为我拼出它的方式......违背了学习编码的目的。
    【解决方案3】:
    public static void main(String args [])
    {
       int [] array = {5,6,7,2,3,1};
       array = sum(array,0);
       for(int i=0; i<array.length; i++){
           System.out.print(" "+array[i]);
       }
    
    }
    
    public static int[] sum(int[] array, int index){
        if(index==array.length){
            return array;
        }
        if(index!=0){
            array[index] += array[index-1];
        }
    
        return sum(array,index+1);
    
    }
    

    输出:5 11 18 20 23 24

    【讨论】:

    • 方法不能是静态的。您的方法将起作用,只是您删除 static 然后在 main 方法中创建该类的实例。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2013-08-07
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多