【问题标题】:how can I get the result of addition and subtraction, with a recursive method that uses an ArrayList?如何使用使用 ArrayList 的递归方法获得加法和减法的结果?
【发布时间】:2024-04-15 10:10:02
【问题描述】:

给定一个 arraylist 输入,我必须创建一个递归方法,该方法返回列表中奇数位置的值的总和,从中减去值的位置

例如:

private int method(ArrayList<Integer> list, int k)
{
    int s = 0;
    s = list.get(k);
    if(k == list.size()) return s;
    return s + method(k+1);
}

public int method(ArrayList<Integer> list)
{
    return method(list,0);
}

(主要)

         List<Integer> list = Arrays.asList(2, 5, 3, 7, 11, 1);
         ArrayList<Integer> l2 = new ArrayList<>(list);
         SumSub test = new SumSub(l2);
         System.out.println(test.method(l2));

[2, 5, 3, 7, 11, 1] ---> 2-5+3-7+11-1=3(应该显示的结果) 但结果总是 22,我不明白为什么

【问题讨论】:

  • 您的代码不应编译,因为您正在调用 method(k+1),但没有带有单个 int 参数的方法。你确定你已经向我们展示了返回 22 的工作代码吗?
  • '从中减去值的位置' - 你的意思是应该减去偶数值,对吧?根据这个解释修正了我的答案。

标签: java list recursion arraylist indexing


【解决方案1】:

一些提示:

  • 为变量提供有意义的名称,而不是 kslist 等。
  • 尽可能声明集合接口 (List) 而不是实现类 (ArrayList),以提高代码中的抽象级别。

这里是递归解决方案的示例(未经测试):

private static int addOddAndSubtractEvenPositions(List<Integer> values, int position) {

    // stop condition
    if (position >= values.size()) {
        return 0;
    }

    // recurse
    int tailResult = addOddAndSubtractEvenPositions(values, position + 1);

    // calculate
    int currentValue = values.get(position);
    if (position % 2 == 0) {
         currentValue = -currentValue;
    }       
    return currentValue + tailResult;   
}

public static void main(String[] args) {
    List<Integer> values = Arrays.asList(2, 5, 3, 7, 11, 1);    
    System.out.println(addOddAndSubtractEvenPositions(values, 0));
}

【讨论】:

  • 非常感谢 Adriaan,我无法解决这个递归问题,当我有疑问时,任何人都无法像递归一样删除它 XD。
【解决方案2】:

没看懂k这个参数是干什么用的 但是一种递归方法来减去对中的元素,然后对所有对求和:

public static int SumSub(ArrayList<Integer> list){

    int result = 0;
    int size = list.size();

    if(list.size() > 2){

        for(int i = 0; i < size; i++){

            ArrayList<Integer> newList1 = new ArrayList<Integer>(list.subList(i, i+2));
            result += SumSub(newList1);
            i++;

        }

    } else {
        result = list.get(0) - list.get(1);
    }

    return result;  
}   

}

【讨论】:

    最近更新 更多