简体   繁体   中英

C# Dynamic programming conversion

Hi I have a task to convert exponential code into linear, but I have no idea how to do it. Could you give me any tips or point me in the right direction?

Here's the code:

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

            else if(m == 0 && n > 0)
            {
                return n;
            }

            else
            {
                int[] array = { 1 + F(m - 1, n), 1 + F(m, n - 1), D(m, n) + F(m - 1, n - 1) };
                return array.Min();
            }
        }

        int D(int i, int f)
        {
            if(x[i] == y[f])
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

Update:

Am I going in the right direction? So far it works only with m=0,1,2 and n=0,1,2. How do I fill all the values if let's say, I give m = 10 and n = 20?

int Fdp(int m, int n)
        {
            fdin[m, 0] = m;

            for(int i = 0; i <= n; i++)
            {
                fdin[0, i] = n;
            }

            if (n == 0)
            {
                return m;
            }

            else if (m == 0 && n > 0)
            {
                return n;
            }

            else
            {

                int[] temp = { 1 + fdin[m-1, n], 1+ fdin[m,n-1], D(m,n) + fdin[m-1,n-1] };
                fdin[m, n] = temp.Min();
                return temp.Min();
            }

        }

Solved it.

        static int Fdp(int m, int n)
        {
            for (int i = 0; i <= m; i++)
            {
                fdin[i, 0] = i;
                for (int j = 1; j <= n; j++)
                {
                    if(i == 0)
                    {
                        fdin[i, j] = j;
                    }
                    else
                    {
                        int[] temp = new int[] { 1 + fdin[i - 1, j], 1 + fdin[i, j - 1], D(i, j) + fdin[i - 1, j - 1] };
                        fdin[i, j] = temp.Min();
                    }
                }
            }
            return fdin[m,n];
        }

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