正如@KlasLindbäck 的回答中所发布的那样,5 应该是 s。
public static int sum(int[]A,int s,int e) {
if (s==e)
return A[e];
else
return A[s] + sum(A,s+1,e);
提供解释:
首先,调用这个方法:
int theSum = sum(myArray, 0, myArray.length-1);
我将为您介绍 {3,5,8,9,10} 数组。
sum(A, 0, 4):
return A[0] + sum(A, 1, 4) //3 + sum(A, 1, 4)
sum(A, 1, 4):
return A[1] + sum(A, 2, 4) //5 + sum(A, 2, 4)
sum(A, 2, 4):
return A[2] + sum(A, 3, 4) //8 + sum(A, 3, 4)
sum(A, 3, 4):
return A[3] + sum(A, 4, 4) //9 + sum(A, 4, 4)
sum(A, 4, 4):
return A[4] //10
Now, we know that sum(A, 4, 4) is 10, so therefore sum(A, 3, 4) is 9 + 10 = 19.
Now, we know that sum(A, 3, 4) is 19, so therefore sum(A, 2, 4) is 8 + 19 = 27.
Now, we know that sum(A, 2, 4) is 27, so therefore sum(A, 1, 4) is 5 + 27 = 32.
Now, we know that sum(A, 1, 4) is 32, so therefore sum(A, 0, 4) is 3 + 32 = 35.