查找斐波納契數列中第 N 個數。
所謂的斐波納契數列是指:
- 前2個數是 0 和 1 。
- 第 i 個數是第 i-1 個數和第i-2 個數的和。
斐波納契數列的前10個數字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
像這樣的題,看到肯定想到遞歸算法來做,這是一種很重要的思想(雖然遞歸實現效率低,但是簡潔的代碼就能達到該有的功能),
下面上源碼。
遞歸算法:
public int fibonacci(int n) { // write your code here if(n == 1) return 0; else if(n == 2) return 1; return fibonacci(n-2)+fibonacci(n-1); }
非遞歸:
public int fibonacci(int n) { // write your code here int a = 0; int b = 1; int result = 0; if(n == 1) return 0; else if(n == 2) return 1; for(int i = 3;i<n+1;i++){ result = a +b; a = b; b = result; } return result; }