Dynamic programming of Algorithms (Java edition)

Source: Internet
Author: User

Overview:

The importance of the algorithm is self-evident.

It may be that you would be too bothered to listen to this, because in our actual development, there are so few places to use algorithms. I do not deny this, because the algorithm is too advanced for a beginner developer. If we want to implement a function, the usual way is Baidu or Google. That's why there's a joke: we don't produce code, we're just code movers.

When we have completed this process for our beginner developers, we should be thinking about how to optimize our code to make our code more beautiful and more of a B-grid.


usage Scenarios for motion gauges:

Dynamic programming is an improvement of backtracking algorithm.

We know that one of the fatal drawbacks of backtracking is its repetitive calculation, which I will illustrate in the following example, and that the rules circumvent the problem. The core of the motion regulation is the state and state transfer equations.


example examples and process descriptions:1. Digital TrianglesProblem Description:

There is a triangle of non-negative integers, with only one number in the first row and one number in the lower left and bottom right of each number except the last line.

Starting with the number of the first row, you can go down or down one block at a time, until you reach the last line, adding up the number of passes along the painting. How can we walk to make this number as big as possible?


thinking Carding:

For such a question, the first solution that you might think of is recursion. For recursion, we don't have to think too much. Because when we want to know the maximum value at (i, j), we depend on the maximum of the nodes (i + 1, j) and the (i + 1, j + 1). And so on, so that we can use recursion and recursion to implement.


Recursive solution (key code)

/**     * The maximum value at (I, j) is obtained by backtracking     * @author Aaron     * August 2, 2015 *    /private static int Getnodemaxbyrecall (int [] m, int i, int j) {        int max = Integer.min_value;                System.out.println ("m[" + i + "[" + j + "]");                max = M[i][j] + (i = = m.length-1? 0:math.max (Getnodemaxbyrecall (M, i + 1, j), Getnodemaxbyrecall (M, i + 1, j + 1)); C8/>return max;    }        /**     * Backtracking Solution     * @author Aaron * August 1, 2015 * * public    static void Calculatebyrecall (int[] a) {        int[][] m = Getmatrix (a);                int max = Getnodemaxbyrecall (m, 0, 0);                System.out.println ("max[0][0] =" + max);    }

As you can see, recursive solution is a top-down approach. It is calculated on an as-needed basis.

In recursion, for example, our intention is to solve Max (I, J), and when we know that we need to solve Max (I, J), we have to know Max (i + 1, j) and Max (i + 1, j + 1) to solve Max (i + 1, j) and Max (i + 1, j + 1).

However, this on-demand solution does not let us know if the points to be computed have been computed. Here is the node process that the program has computed during the recursive process:


As you can see, some of the nodes here are duplicated.


Recursive method solution (key code):

/**     * The maximum value at (I, j) is obtained by recursive method     * @author Aaron     * August 2, 2015 *    /private static int getnodemaxbyrecursion ( Int[][] m, int i, int j) {        int max = Integer.min_value;                System.out.println ("m[" + i + "[" + j + "]");                max = M[i][j] + (i = = M.length-1 0:math.max (m[i + 1][j], m[i + 1][j + 1]));                return max;    }        /** *     Recursive solution     * @author Aaron     * August 2, 2015 * *    /private static void Calculatebyrecursion (int[] a) {        int[][] m = Getmatrix (a);                for (int i = m.length-1; I >= 0, i--) {for            (int j = 0; J <= I; j + +) {                M[i][j] = getnodemaxbyrecursion (M , I, j);            }        }                int max = m[0][0];                System.out.println ("max[0][0] =" + max);    }

As you can see, the recursive solution is a bottom-up approach. It is calculated in advance.

In recursion, for example, our intention is to solve Max (I, J), when we know that we need to solve Max (I, J), we have to know Max (i + 1, j) and Max (i + 1, j + 1), but this time, our max (i + 1, j) and Max (i + 1, j + 1) has been calculated, this time we will not have to calculate.

In the recursive calculation process, because we are the bottom-up solution, we do not know whether this node will be used, and if the node needs to be used, we will not repeat the calculation of this value, because it has been calculated, and has been saved. However, in this process, each node is evaluated once, regardless of whether it is used (although it is used in this program).


as you can see, each node here has and is called only once. There are some advantages to the complexity of the time.


Memory Solution (key code):

/** * Maximum value at (I, j) by memory search * @author Aaron * August 2, 2015 */private static        int getnodemaxbymemory (int[][] m, int[][] D, int i, int j) {if (D[i][j] >= 0) {return d[i][j];                } System.out.println ("m[" + i + "[" + j + "]"); D[I][J] = M[i][j] + (i = = m.length-1? 0:math.max (Getnodemaxbymemory (M, D, i + 1, j), Getnodemaxbymemory (M, D, i + 1,                J + 1));    return D[I][J];        /** * Memory Search * @author Aaron * August 2, 2015 * * * * private static void Calculatebymemory (int[] a) {                int[][] m = getMatrix2 (a);                Int[][] D = Initmatrix (m.length);                int max = Getnodemaxbymemory (M, D, 0, 0);    System.out.println ("max[0][0] =" + max); }

The memory search is based on the recursive return. Because we want to do something to avoid the repetition of the previous recursion in the calculation. In learning the complexity of the algorithm, we know that the complexity is divided into two kinds, one is the time complexity, one is the space complexity. There is a balance between the two kinds of complexity. That is to say we want to optimize in time, then we have to make sacrifices in space. This is where the sacrifice of space is used in exchange for time priority.

The following are the processes that are computed for each node:


As you can see here, each of our nodes is counted only once. Save time.


2. Steel Bar CuttingProblem Description:

Given a length of n-inch steel bars and a price table P (i), the plan to cut the steel bar, so that the sales yield R (N) the largest. Note that if the price of a steel bar of length n is large enough for P (N), the optimal solution may not be completely non-cutting.

Price list:

See this question, do not know whether people are also like me, the first feeling is can use greedy try. But after the thought and found that it will not work, because if the cutting of steel rods in different ways, then cut into two parts is a variable amount, bad control.

According to the above ideas, we can use two methods to try to solve this problem:

recursion (Key code):

/**     * Optimal cutting scheme for calculating steel bars of length n (recursive)     * @author Aaron     * August 3, 2015 *    /private static int Getmax (int[] p, int n) {        System.out.println (n);        if (n <= 0) {            return 0;        }                int max = Integer.min_value;                for (int i = 1; I <= n; i++) {            max = Math.max (max, p[i-1] + getmax (p, n-i));        }                return max;    }        /**     * Calculation of the cutting algorithm for steel bars by recursion     * @author Aaron     * August 3, 2015 */    private static void calculatemaxbyrecursive (int n) {        initpricelist ();        Int[] p = {1, 5, 8, 9, ten,                , int max = Getmax (p, n);                System.out.println ("max =" + max);    }

Memory Search (Key code):

private static int[] Getrecordarray (int n) {if (n <= 0) {return null;        } int[] r = new Int[n];        for (int i = 0; i < n; i++) {r[i] = Integer.min_value;    } return R; }/** * Optimal cutting scheme for calculating steel bars of length n (Memory search) * @author Aaron * August 3, 2015 */private static int getmaxbymemory (int[] p, int n, int[] r)        {if (n <= 0) {return 0;        } if (R[n] >= 0) {return r[n];                } System.out.println (n);                int max = Integer.min_value;        for (int i = 1; I <= n; i++) {max = Math.max (max, p[i-1] + getmaxbymemory (p, n-i, R));                } R[n] = max;    return Max; /** * Calculation of the cutting algorithm for the steel bar by memory search * @author Aaron * August 3, 2015 */private static void Calculatemaxbymemory (int n)        {initpricelist (); Int[] p = {1, 5, 8, 9, 10, 17, 17, 20, 24,30};                Int[] r = Getrecordarray (n + 1);                int max = Getmaxbymemory (p, N, R);    System.out.println ("max =" + max); }


full Source code download:

http://download.csdn.net/detail/u013761665/8957807


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. http://blog.csdn.net/lemon_tree12138

Dynamic programming of Algorithms (Java edition)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.