New Solution of Fibonacci Sequence (Dynamic Programming)

Everyone is familiar with the Fibonacci sequence.

f(n) = f(n-1) + f(n-2)

f(0) = 1

f(1) = 1

If you want to use a computer program to realize this function, it is easy to think of using recursion according to the above recursion formula. The advantage of using recursion is that programmers do not need to consider the specific calculation process, as long as they find a clear exit for recursion. up.

int fib(int n)
{
    if (n == 0 || n == 1) {
        return 1;
    }

    return fib(n - 1) + fib(n - 2);
}

The disadvantage of recursion is that it involves the overhead of function calls, and the execution efficiency is relatively low.

Of course, the iterative method can also be used to solve the problem. Iteration starts from the solution of the known problem and continuously deduces the solution of the unknown problem. To put it simply, recursion is a top-down process, and iteration is a bottom-up process. .

int fib(int n)
{
    int temp1 = 1;
    int temp2 = 1;
    
    for (int i = 2; i < n; i++) {
        int temp = temp1 + temp2;
        temp1 = temp2;
        temp2 = temp;
    }
    
    return temp1 + temp2;
}

The iterative method does not have the process of calling itself, so the efficiency is much higher than that of recursion;,

Let's look back at the implementation of recursion. If you want to solve fib(5), you need to get fib(4) and fib(3). To solve fib(4), you need to get fib(3) and fib(2). To solve fib( 3) You need to get fib(2) and fib(1), and you need to get fib(1) and fib(0) to solve fib(2). Solving fib(3) also needs to go through such a process, which will inevitably cause repeated calculations and repeated function stacking and popping. If we save the solved results during the calculation and then use these results directly in the calculation, it will be much more efficient. This method is called dynamic programming.

int fib(int n, int *table)
{
    if (table[n]) {
        return table[n];
    }

    table[n] = fib(n - 1) + fib(n - 2);

    return table[n];
}

int get_value(int n)
{
    int *table = (int *)malloc(sizeof(int) * (n + 1));
    table[0] = 1;
    table[1] = 1;

    return fib(n, table);
}

Guess you like

Origin blog.csdn.net/daida2008/article/details/100850058