---恢复内容开始---
要求:
已知数组 int[ ] a,
输出:a[0]+a[1]+...+a[end]的值
方法1:a[begin] + { a[begin+1]...a[end] }
1 import java.util.Scanner; 2 //递归求数组和 3 public class demo1 { 4 5 public static int f(int[]a,int begin){ 6 if(begin==a.length) 7 return 0; 8 int x = f(a,begin+1); 9 return x+a[begin]; 10 } 11 public static void main(String[] args) { 12 int []a = {1,2,3,4,5}; 13 int sum = f(a,0); 14 System.out.println(sum); 15 } 16 17 }
方法2:{ a[0] ... a[end-1] } + a[end]
1 import java.util.Scanner; 2 //递归求数组和 3 public class demo1 { 4 5 public static int f(int[]a,int end){ 6 if(end==-1) 7 return 0; 8 int x = f(a,end-1); 9 return x+a[end]; 10 } 11 public static void main(String[] args) { 12 int []a = {1,2,3,4,5}; 13 int sum = f(a,a.length-1); 14 System.out.println(sum); 15 } 16 17 }
方法3:折半求和,mid = (begin+end)/2,(a[begin]...a[mid]]+(a[mid]+a[end]]
1 import java.util.Scanner; 2 //递归求数组和 3 public class demo1 { 4 5 public static int f(int[]a,int begin,int end){ 6 int mid = (begin+end)/2; 7 if(begin>end) 8 return 0; 9 if(begin==end) 10 return a[end]; 11 else 12 return f(a,begin,mid)+f(a,mid+1,end); 13 } 14 public static void main(String[] args) { 15 int []a = {1,2,3,4,5}; 16 int sum = f(a,0,a.length-1); 17 System.out.println(sum); 18 } 19 20 }
---恢复内容结束---