简体   繁体   中英

How to calculate complexity of an algorithm?

I've trying to calculate complexity of an algorithm, but I'm not sure how to do that. I know how to solve simple algorithms, but I'm struggling with recursion.

There is the code of recursion:

static int F(int m, int n)
    {
        if (n == 0)
            return m;

        if (m == 0 && n > 0)
            return n;

        else
            return Math.Min((1 + F(m - 1, n)), Math.Min((1 + F(m, n - 1)), (D(m - 1, n - 1) + F(m - 1, n - 1))));
    }

Can someone explain me or help me to calculate this function? I've tried googling it but I can find only simple examples.(maybe mine code is also simple?)

Thank you!

I don't know what the D function is in your first piece of code. I'll consider it as a constant function.

The first piece of your code is equivalent to the following one.

static int F(int m, int n)
{
    if (n == 0 || m == 0)
        return n + m;
    else
        return Math.Min((1 + F(m - 1, n)), Math.Min((1 + F(m, n - 1)), (D(m - 1, n - 1) + F(m - 1, n - 1))));
}

It's a little difficult to calculate the time complexity of a recursive function with two parameters, but we can estimate it roughly. We have the following equation.

T(n, m) = T(n-1, m) + T(n, m-1) + T(n-1, m-1)

We can discover that the equation is quite similar to the recursive equation of binomial coefficient , but with even larger result. This tells us that the time complexity of the algorithm is an exponential function, which is quite slow.

But actually, you can use some tricks to reduce its time complexity to O(mn).

bool calculated[MAX_M][MAX_N];
int answer[MAX_M][MAX_N]

static int F(int m, int n)
{
    if (n == 0 || m == 0)
        return n + m;
    else
    {
        if (calculated[m][n] == false)
        {
            answer[m][n] = Math.Min((1 + F(m - 1, n)), Math.Min((1 + F(m, n - 1)), (D(m - 1, n - 1) + F(m - 1, n - 1))));
            calculated[m][n] = true;
        }
        return answer[m][n];
    }
}

I can't quite understand what the second piece of code is going to do as there are lots of functions unprovided in your code. Maybe you can explain that a bit?

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