# 首先咱們直接看一個demo以及他的結果函數
public class QQ { public static void main(String[] args) throws ParseException { // 1,1,2,3,5,8 ... int n = 50; Long start = System.currentTimeMillis(); System.out.println(fun(n)); System.out.println("time1 : " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println(fun2(n)); System.out.println("time2 : " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println(fun3(n)); System.out.println("time3: " + (System.currentTimeMillis() - start)); } public static long fun(int n) { if (n <= 2) { return 1L; } else { return fun(n - 1) + fun(n - 2); } } public static long fun2(int n) { if (n <= 2) { return 1L; } else { long a = 1, b = 1, c = 0; for (int i = 3; i <= n; i++) { c = a + b; a = b; b = c; } return c; } } public static long fun3(int n) { if (n <= 2) { return 1L; } else { long[] arr = new long[n + 1]; arr[1] = 1; arr[2] = 1; for (int i = 3; i <= n; i++) { arr[i] = arr[i - 1] + arr[i - 2]; } return arr[n]; } } }
# 上面代碼的計算結果是:spa
12586269025
time1 : 46059
12586269025
time2 : 0
12586269025
time3: 0code
# 分析:blog
- 能夠看出使用遞歸計算須要的時間最長遞歸
- 咱們不進行理論的分析,再用一個簡單的例子去簡要說明一下爲何遞歸須要的時間這麼長io
public class QQ { private static long count = 0L; public static void main(String[] args) throws ParseException { // 1,1,2,3,5,8 ... int n = 50; Long start = System.currentTimeMillis(); System.out.println(fun(n)); System.out.println("time1 : " + (System.currentTimeMillis() - start)); System.out.println("count: " + count); } public static long fun(int n) { count++; if (n <= 2) { return 1L; } else { return fun(n - 1) + fun(n - 2); } } }
# 上面代碼的輸出結果是:class
12586269025
time1 : 48285
count: 25172538049循環
# 分析:
- 能夠看出fun這個函數被調用了不少次,可是這個函數基本上只有一個邏輯,咱們來看看這個比較邏輯調用 25172538049 次會發生些什麼吧im
public class QQ { public static void main(String[] args) throws ParseException { // 1,1,2,3,5,8 ... int n = 50; Long start = System.currentTimeMillis(); for (long i = 0; i < 25172538049L; i++) { } System.out.println("time1 : " + (System.currentTimeMillis() - start)); } }
# 上面代碼的輸出結果爲:
time1 : 10358demo
# 分析:
- 上面的代碼循環中一共包含兩個調用次數較多的邏輯;第一個是比較邏輯,第二個是 自增 邏輯, 能夠看出,兩個很簡單的邏輯調用 25172538049 次就會耗時這麼多,那麼遞歸調用加上調用函數的各類開銷,一共須要這麼長的時間好像也就不足爲奇了