递归
找重复->找重复中的变化量->参数变化趋势
练习3:数组求和
public static void main(String[] args) {int[] arr = {1,2,3,4,5,6,7,8,9,10};int n = arr.length;System.out.println(sum(arr,0,n));}public static int sum(int arr[],int start,int end){if(start == end-1)return arr[start];else return arr[start] + sum(arr,start+1, end);}
练习4:翻转字符串
public static void main(String[] args) {StringBuffer s = new StringBuffer("abcdef");System.out.println(reversestr(s,0,s.length()));}public static StringBuffer reversestr(StringBuffer str,int start,int end){if(start==end-1){StringBuffer res = new StringBuffer(String.valueOf(str.charAt(start)));return res;}else{return reversestr(str,start+1,end).append(str.charAt(start));}}
练习5:斐波那契数列
public static void main(String[] args) {for(int i=1;i<10;i++) System.out.println(fib(i));}
public static int fib(int n){if(n==1)return 1;else if(n==2)return 1;else return fib(n-1)+fib(n-2);
}
练习6:最大公约数
public static void main(String[] args) {System.out.println(gcd(10,20));}public static int gcd(int m,int n){if(n==0)return m;else return gcd(n,m%n);}
练习7:递归形式进行插入排序
public static void main(String[] args) {int[] arr = {1,5,2,6,3,9,11};sort1(arr,arr.length-1);for(int i=0;i<arr.length;i++) System.out.println(arr[i]);}public static void sort1(int arr[],int idx){if(idx==0) return;else{sort1(arr,idx-1);int temp = arr[idx];int i=idx-1;while(arr[i]>arr[idx]){arr[i+1]=arr[i];i--;}arr[i+1]=temp;}}
练习8:汉诺塔
public static void main(String[] args) {hanoi(3,'a','b','c');}public static void hanoi(int n,char c1, char c2, char c3){if(n==1)System.out.println(""+c1+"->"+c3);else{hanoi(n-1,c1,c3,c2);System.out.println(""+c1+"->"+c3);hanoi(n-1,c2,c1,c3);}}