Recursive Fibonacci memoization

后端 未结 14 1462
走了就别回头了
走了就别回头了 2020-11-30 02:47

I need some help with a program I\'m writing for my Programming II class at universtiy. The question asks that one calculates the Fibonacci sequence using recursion. One mus

14条回答
  •  心在旅途
    2020-11-30 03:25

    public class FiboSeries {
    
        // first two terms of Fibonacci
        int x1 = 0;
        int x2 = 1;
        long xn; // nth number in Fibo series
        long[] array; // an array for implementing memoization
    
        // print the Nth number of Fibonacci - logic is f(n) = f(n-1) + f(n-2)
    
        long fibo(int n) {
    
            // initialize the array having n elements if it does not exist already
            if (array == null) {
    
                array = new long[n + 1];
    
            }
    
            // Fetch the memoized value from the array instead of recursion
            // for instance, fibo(3) will be calculated just once and stored inside this
            // array for next call
            if (array[n] != 0)
    
            {
                xn = array[n];
                return xn;
            }
    
            // value of fibo(1)
            if (n == 1) {
                xn = x1;
    
            }
    
            // value of fibo(2)
            if (n == 2) {
                xn = x2;
    
            }
    
            // value of Fibo(n) using non linear recursion
            if (n > 2) {
    
                xn = fibo(n - 1) + fibo(n - 2);
            }
    
            // before returning the value - store it at nth position of an array
            // However, before saving the value into array, check if the position is already 
            //full or not
    
            if (array[n] == 0) {
    
                array[n] = xn;
            }
    
            return xn;
    
        }
    
        public static void main(String[] args) {
    
            FiboSeries f = new FiboSeries();
    
            int n = 50;
            long number = f.fibo(n);
    
            System.out.println(number);
    
        }
    
    
    }
    

提交回复
热议问题