递归的经典题目总结
注意:構造方法不可遞歸,否則是無限創建對象;
遞歸的幾個經典例子:
1.HannoiTower?
import?java.util.Scanner; public?class?HanoiTower{ //level代表盤子個數;三個char類型代表柱子 public?static?void?moveDish(int?level,?char?from,?char?inter,?char?to){ if(level?==?1){ System.out.println("從"+from+"移動盤子1號到"+to); }else{ moveDish(level-1,from,to,inter);//調用自身 System.out.println("從"+from+"移動盤子"+level+"號到"+to); moveDish(level-1,inter,from,to); } } public?static?void?main(String[]?args){ Scanner?sc?=?new?Scanner(System.in); System.out.println("請輸入盤子個數"); int?n?=?sc.nextInt(); moveDish(n,'a','b','c'); } }2.sum?
import?java.util.Scanner; public?class?Sum{ public?static?void?main(String[]?args){ Scanner?sc?=?new?Scanner(System.in); System.out.println("請輸入n:"); int?n?=?sc.nextInt(); int?sum1?=?sum(n); System.out.println(sum1; } public?static?int?sum(int?n){ if(n?==?1){ return?1; }else{ return?n+sum(n-1); } } }3.factorial?
import?java.util.Scanner; public?class?Factorial{ public?static?void?main(String[]?args){ Scanner?sc?=?new?Scanner(System.in); System.out.println("請輸入一個小于20的整數,我會幫你求出它的階乘:"); int?n?=?sc.nextInt(); int?fac1?=?fac(n); System.out.println(n+"的階乘為:"+fac1); System.out.println("~看我棒不棒~~"); } public?static?int?fac(int?n){ if(n?==?1){B return?1; }else{ return?n*fac(n-1); } } }4.sumFactorial?
import?java.util.Scanner; public?class?SumFactorial{ public?static?void?main(String[]?args){ Scanner?sc?=?new?Scanner(System.in); System.out.println("請輸入一個小于20的整數:"); int?n?=?sc.nextInt(); int?sf?=?sumFac(n); System.out.println(sf); } //階乘和的累加 public?static?int?sumFac(int?n){ if(n?==?1){ return?1; }else{ return?fac(n)+sumFac(n-1); } } //求階乘 public?static?int?fac(int?n){ if(n?==?1){ return?1; }else{ return?n*fac(n-1); } } }5.使用遞歸,遍歷 1 至100之間的每個數字
public?class?Number{ public?static?void?main(String[]?args){ iterator(100); } public?static?void?iterator(int?n){ if(n?>=?1){ System.out.print(n+"\t"); n--; iterator(n); } } }轉載于:https://blog.51cto.com/huguangqin2015/1940996
總結
- 上一篇: Mysql 存储引擎和事物基础概念
- 下一篇: Java并发编程之:Vector和Arr