给定一个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] ---&gt; 2-5 + 3-7 + 11-1 = 3(应该显示的结果) 但结果总是22,我不明白为什么
答案 0 :(得分:1)
一些指示:
k
,s
,list
等。这是一个递归解决方案的示例(未经测试):
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));
}
答案 1 :(得分:0)
我还没有理解参数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;
}
}