简体   繁体   中英

Fibonacci number using dp in C++

I have written two functions for Fibonacci numbers, one using recursion and the second using memorization(dynamic programming). Since the 2nd is using dp so it should run faster than the first one but the fact is the 2nd one takes more time than the 1st one.

Please correct me, if I have done some mistakes while writing functions.

Thanks in advance :)

Function 1:

long fibb(int n)
{
    if (n <= 2)
        return 1;
    return fibb(n - 1) + fibb(n - 2);
}

Function 2:

// long fib(int n, unordered_map<int, long> mp) (wrong)
long fib(int n, unordered_map<int, long> &mp) // correct
{
    if (mp.find(n) != mp.end())
        return mp[n];
    if (n <= 2)
        return 1;
    mp[n] = fib(n - 1, mp) + fib(n - 2, mp);
    return mp[n];
}

Edit:- I attached the above code, earlier only images were there. Solution:- I got the answer as I was missing the ampersand(&) from the arguments.

Function 1:

在此处输入图像描述

Function 2:

在此处输入图像描述

long fib(int n, unordered_map<int, long>& mp) will be faster. Notice the & which passes the map by reference. This avoids a costly copy, and most importantly, avoids the modifications to the map from being lost.

You are passing the std::unordered_map by value. This means your code will always skip the if statements and go straight to fetching the Fibonacci number using the recursive function. You are still using the function that you thought you had avoided (at least when trying to fetch the same number twice from the unordered_map ) which has its own cost plus the cost of setting up the stack frame of the function and copying the map each time. The second function is indeed slower.

Pass the unordered_map as a reference to avoid copying and most importantly, save the changes or the new values to the map.

long fib(int n, unordered_map<int, long> &mp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM