Recursive Fibonacci memoization

后端 未结 14 1405
走了就别回头了
走了就别回头了 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:12
    int F(int Num){
    int i =0;
    int* A = NULL;
    if(Num > 0)
    {
     A = (int*) malloc(Num * sizeof(int));
    }
    else
     return Num;
    
    for(;i<Num;i++)
     A[i] = -1;
    
    return F_M(Num, &A);
    
    
    }
    
    int F_M(int Num, int** Ap){
    int Num1 = 0;
    int Num2 = 0;
    
    if((*Ap)[Num - 1] < 0)
    {
      Num1 = F_M(Num - 1, Ap);
      (*Ap)[Num -1] = Num1;
      printf("Num1:%d\n",Num1);
    }
    else
      Num1 = (*Ap)[Num - 1];
    
    if((*Ap)[Num - 2] < 0)
    {
      Num2 = F_M(Num - 2, Ap);
      (*Ap)[Num -2] = Num2;
      printf("Num2:%d\n",Num2);
    }
    else
      Num2 = (*Ap)[Num - 2];
    
    if(0 == Num || 1 == Num)
    {
     (*Ap)[Num] = Num;
     return Num;
    }
    else{
    //  return ((*Ap)[Num - 2] > 0?(*Ap)[Num - 2] = F_M(Num -2, Ap): (*Ap)[Num - 2]  ) +     ((*Ap)[Num - 1] > 0?(*Ap)[Num - 1] = F_M(Num -1, Ap): (*Ap)[Num - 1]  );
      return (Num1 + Num2);
    }
    
    }
    
    int main(int argc, char** argv){
    int Num = 0;
    if(argc>1){
    sscanf(argv[1], "%d", &Num);
    }
    
    printf("F(%d) = %d", Num, F(Num));
    
    return 0;
    
    }
    
    0 讨论(0)
  • 2020-11-30 03:18

    Here is a fully-fledged class that leverages the memoization concept:

    import java.util.HashMap;
    import java.util.Map;
    
    public class Fibonacci {
    
        public static Fibonacci getInstance() {
            return new Fibonacci();
        }
    
        public int fib(int n) {
            HashMap<Integer, Integer> memoizedMap = new HashMap<>();
    
            memoizedMap.put(0, 0);
            memoizedMap.put(1, 1);
    
            return fib(n, memoizedMap);
        }
    
        private int fib(int n, Map<Integer, Integer> map) {
            if (map.containsKey(n))
                return map.get(n);
    
            int fibFromN = fib(n - 1, map) + fib(n - 2, map);
    
            // MEMOIZE the computed value
            map.put(n, fibFromN);
    
            return fibFromN;
        }
    }
    

    Notice that

    memoizedMap.put(0, 0);
    memoizedMap.put(1, 1);
    

    are used to eliminate the necessity of the following check

    if (n == 0) return 0;
    if (n == 1) return 1;
    

    at each recursive function call.

    0 讨论(0)
  • 2020-11-30 03:21

    Program to print first n fibonacci numbers using Memoization.

    int[] dictionary; 
    // Get Fibonacci with Memoization
    public int getFibWithMem(int n) {
        if (dictionary == null) {
            dictionary = new int[n];
        }
    
        if (dictionary[n - 1] == 0) {
            if (n <= 2) {
                dictionary[n - 1] = n - 1;
            } else {
                dictionary[n - 1] = getFibWithMem(n - 1) + getFibWithMem(n - 2);
            }
        }
    
        return dictionary[n - 1];
    }
    
    public void printFibonacci()
    {
        for (int curr : dictionary) {
            System.out.print("F[" + i++ + "]:" + curr + ", ");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 03:22
    import java.util.HashMap;
    import java.util.Map;
    
    public class FibonacciSequence {
    
        public static int fibonacci(int n, Map<Integer, Integer> memo) {
            if (n < 2) {
                return n;
            }
            if (!memo.containsKey(n)) {
                memo.put(n, fibonacci(n - 1, memo) + fibonacci(n - 2, memo));
            }
            return memo.get(n);
        }
    
        public static int fibonacci(int n, int[] memo) {
            if (n < 2) {
                return n;
            }
            if (memo[n - 1] != 0) {
                return memo[n - 1];
            }
            return memo[n - 1] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
        }
    
        public static void main(String[] s) {
            int n = 10;
    
            System.out.println("f(n) = " + fibonacci(n, new HashMap<Integer, Integer>()));
            System.out.println("f(n) = " + fibonacci(n, new int[n]));
        }
    }
    
    0 讨论(0)
  • 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);
    
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-30 03:28

    In Swift 5.3

    This is a very quick one using memoisation. First I initialise my cache dictionary.

    var cache = [Int:Int]()
    

    Then I create my Fibonacci number generator. Since it is a recursive function, every call to the function would theoretically compute the whole Fibonacci sequence again up to the requested number. This is why we use the cache, to speed up the recursive function:

    func fibonacci(_ number: Int) -> Int {
        // if the value is in the dictionary I just return it
        if let value = cache[number] { return value }
    
        // Otherwise I calculate it recursively. 
        // Every recursion will check the cache again, 
        // this is why memoisation is faster!
        let newValue = number < 2 ? number : fibonacci(number - 1) + fibonacci(number - 2)
        cache[number] = newValue
        return newValue
    }
    

    I can save my sequence in an array like this:

    var numbers = Array(0..<10).map(fibonacci) //[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    Or use the function in a loop.

    0 讨论(0)
提交回复
热议问题