1 public class RecursionTest { 2 3 4 /** 5 * 求n的阶乘 6 */ 7 private static int jiecheng(int n) { 8 if (n==1) { 9 return 1; 10 } 11 return n*jiecheng(n-1); 12 } 13 14 /** 15 * 1 1 2 3 5 8 13 21 34 55 89 144 16 * 求斐波那契数列的第N项 17 * @param n 18 * @return 19 */ 20 private static int feibonaqi(int n) { 21 if(n==1 || n==2) { 22 return 1; 23 }else { 24 return feibonaqi(n-1)+feibonaqi(n-2); 25 } 26 } 27 28 /** 29 * 汉诺塔问题 30 * @param n 一共有N个盘子 31 * @param start 初始位置 32 * @param middle 中介 33 * @param end 目标位置 34 */ 35 private static void hanota(int n, String start, String middle, String end) { 36 if (n==1) { 37 System.out.println("move from "+start+" to "+end); 38 }else { 39 hanota(n-1, start, end, middle); 40 System.out.println("move from "+start+" to "+end); 41 hanota(n-1, middle, start, end); 42 } 43 } 44 45 46 public static void main(String[] args) { 47 System.out.println(jiecheng(5)); 48 System.out.println(feibonaqi(5)); 49 System.out.println(feibonaqi(30)); 50 hanota(7, "left", "middle", "right"); 51 } 52 }