標籤:斐波那契數 備忘 遞迴 一個 斐波那契 demo rip 緩衝 start
為什麼說 “演算法是程式的靈魂這句話一點也不為過”,請看下面這個簡單的案例
1 package recursion; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import org.junit.Test; 7 8 /** 9 * @author: MengXianman10 * @creationTime: 2017年11月27日 上午9:47:5111 * @description: 斐波那契數列結合備忘錄演算法的簡單使用12 */13 public class MemorandumDemo {14 //計算方法執行次數15 private long count;16 //map集合作為一個備忘錄,用來儲存已經計算出來的fibo(n)的值17 private Map<Integer, Long> map = new HashMap<>();18 19 //方式一:不使用map集合作為備忘錄快取資料20 public long fibo(Integer n) {21 count++;22 if(n == 1 || n == 2){23 return 1;24 }else{ 25 return fibo(n-1) + fibo(n-2);26 }27 }28 //方式二:使用map集合作為備忘錄快取資料29 public long fibo2(Integer n) {30 count++;31 if(n == 1 || n == 2){32 return 1;33 }else{ 34 if(!map.containsKey(n)){35 map.put(n, fibo2(n-1) + fibo2(n-2));36 }37 return map.get(n);38 }39 }40 41 @Test42 public void test1(){43 long start = System.currentTimeMillis();44 long result = fibo(50);45 long end = System.currentTimeMillis();;46 System.out.println("計算結果:" + result);47 System.out.println("耗費時間:" + (end-start) + "毫秒");48 System.out.println("方法執行次數:"+count);49 /*測試結果50 * 計算結果:1258626902551 * 耗費時間:77318毫秒52 * 方法執行次數:2517253804953 */54 }55 56 @Test57 public void test2(){58 long start = System.currentTimeMillis();59 long result = fibo2(50);60 long end = System.currentTimeMillis();;61 System.out.println("計算結果:" + result);62 System.out.println("耗費時間:" + (end-start) + "毫秒");63 System.out.println("方法執行次數:" + count);64 /*測試結果65 * 計算結果:1258626902566 * 耗費時間:0毫秒67 * 方法執行次數:9768 */69 }70 }
java程式員到底該不該瞭解一點演算法(一個簡單的遞迴計算斐波那契數列的案例說明演算法對程式的重要性)