2016-09-06 9 views
1

我需要編寫java方法來計算用戶輸入的任意前兩個數字的斐波那契數列,假設用戶輸入1020,並且希望系列的前5個數字,輸出將是10 20 30 50 80。我已經實現了這樣做的迭代方法,但是我的問題是使用RECURSIVE方法來完成它。任意前兩個數字的java斐波納契

public int fRec(int n) 
    { 
     //base case of recursion 
     if ((n == 0) || (n == 1)) 
      return n; 
     else 
      //recursive step 
      return fRec(n-1) + fRec(n-2); 
    } 

這是典型的遞歸方法斐波納契數列中,n參數代表了用戶想要什麼號系列運行,但我怎麼可以對其進行修改,以確保該系列採用第一用戶希望該系列開頭的兩個數字?

+1

注:如果您使用遞歸沒有背誦的方法將採取'O(E 1 N)'這是快速長於宇宙的年齡。 –

回答

2

首先在一系列具體的數字,他們需要爲0和1退貨:

public int fib(int n, int start1, int start2) { 
    switch (n) { 
     case 0: return start1; 
     case 1: return start2; 
     default: return fib(n-1, start1, start2) + fib(n-2, start1, start2); 
    } 
} 

這是計算該系列的幾名成員,因爲它是將所有的方式回到一個非常費力的方式每次開始。更好的方式是在一個類來封裝:

class Fib { 
    private int previous; 
    private int current; 

    public Fib(int start1, int start2) { 
     this.previous = start1; 
     this.current = start2; 
    } 

    public int next() { 
     int temp = previous + current; 
     previous = current; 
     current = successor; 
     return current; 
    } 
} 
+0

啊我看到了,我知道這是愚蠢的東西,但看不到它。謝謝!! –

3

我會用memoizationMap<Integer,Long>並通過firstsecond方面的構造。例如,

public class Fibonacci { 
    public Fibonacci(long first, long second) { 
     memo.put(0, first); 
     memo.put(1, second); 
    } 
    Map<Integer, Long> memo = new HashMap<>(); 

    public long fRec(int n) { 
     if (n < 0) { 
      return -1; 
     } 
     if (memo.containsKey(n)) { 
      return memo.get(n); 
     } 
     long r = fRec(n - 2) + fRec(n - 1); 
     memo.put(n, r); 
     return r; 
    } 

    public static void main(String[] args) { 
     Fibonacci f = new Fibonacci(10, 20); 
     for (int i = 0; i < 5; i++) { 
      System.out.println(f.fRec(i)); 
     } 
    } 
} 

,其輸出(如需要)

10 
20 
30 
50 
80 
0

這是計算斐波納契數列的任何第一兩個數的另一種方法。

公共類的StackOverflow {

public static void main(String[] args) { 

    int first = 10, second = 20; 
    System.out.println(first); 
    System.out.println(second); 
    recursive(first, second, 2); 
} 

public static void recursive(int first, int second, int count) { 
     if (count != 5){ 
      int temp = first+second; 
      first= second; 
      second = temp; 
      System.out.println(second); 
      recursive(first, second, ++count); 
     }  
} 

}