時空權衡——斐波那契數列(Time/Space Tradeoff - Fibonacci Sequence)

時空權衡——斐波那契數列(Time/Space Tradeoff - Fibonacci Sequence)


斐波那契數列簡介(Introduction)
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called Fibonacci sequence, characterised by the fact that every number after first two is the sum of the two preceding ones:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233…
The problem is finding the nth Fibonacci number.

算法(Algorithm)
We can use “time and space tradeoff” design algorithm technique, which is decreasing the time required to solve a problem by using additional memory in a clever way.

We use a table to tabulate the function FIB as we go: Once an intermediate result has been computed, it not only return the result to caller but also store it in the table. So each call to FIB first check if the needed value is there, if it is not, the usual recursive process is executed.

僞代碼(Pseudocode)
Suppose all entries of the table are initialised 0.

function Fibonacci(n)
    if n=0 or n=1 then
        return 1
    result ⟵ F[n]
    if result = 0 then
        result ⟵ Fibonacci(n-1) + Fibonacci(n-2)
        F[n] ⟵ result
    return result 

時間複雜度(Time Complexity)
It is linear time O(n). But need an additional memory for array F.

Java code

public class TimeSpaceTradeoff{
    public static int[] F = new int[100];
    public static int Fibonacci(int n){
        if(n==0||n==1)
            return 1;
        int result = F[n];
        if(result==0){
            result = Fibonacci(n-1)+Fibonacci(n-2);
            F[n] = result;
        }
        return result;
    }

    public static void main(String[] args){
        for(int i=0; i<F.length; i++)
            F[i] = 0;
        F[0]=1;F[1]=1;
        int number = Fibonacci(7);
        System.out.println("The 10th Fibonacci number is: "+ number);   
    }
}

運行結果(Result)

21

寫在最後的話(PS)
We can also use brute force algorithm to get the nth Fibonacci number but it is exponential time. We talk about it in “Brute force” chapter.
Welcome questions always and forever.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章