Java - 递归方法,它在一个数组中获取累积和并返回另一个数组

时间:2014-03-04 03:53:21

标签: java arrays recursion

所以这就是问题所在:创建一个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]。

需要注意的是:不能使用static或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]

我所要求的是推动正确的方向,因为我对此感到非常失落。你的帮助会很大的帮助。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

相关问题