Solution to the dynamic programming problem in Leetcode (3)

Source: Internet
Author: User

Dynamic programming is a very important algorithm design idea. Historically there have been many well-known algorithms based on this idea, such as: Needleman–wunsch algorithm, CYK algorithm, FFT algorithm, Viterbi algorithm and so on. There are two core ideas in dynamic programming: First, to disassemble a large problem into several sub problems, and then to store the results that have been calculated for multiple use.


In previous articles in this series, we have introduced a basic routine of dynamic programming algorithm design. But in reality the dynamic programming problem is in fact all sorts of. The answers to the previous move regulations used recursion, and the two examples that are added to this article use loops.


The first is the #718 question in Leetcode (Maximum Length of repeated subarray). The description of the problem is as follows:


A core idea of dynamic programming is to store the results of previous calculations for reuse. This is basically to use space to change time. In this case, in order to store the results that have been calculated, we design a matrix and initialize all of the elements to 0. If the element a[i in array A] is the same as the element b[j in array b, updating an element in the matrix [I,j] to 1+[i-1,j-1],1 represents the current character match, while [I-1,j-1] represents the longest matching substring. This is actually the state transition equation of the moving gauge. The specific implementation code is as follows:

Class Solution {public
:
    int findlength (vector<int>& A, vector<int>& B) {

    	int m = a.size ();
    	int n = b.size ();

    	int * * Matrix = new Int*[m+1];
        
        for (int i = 0; i < m+1 i++)
        {
            Matrix[i] = new int[n+1];
            for (int j = 0; J < N+1; J +)
            {
                	matrix[i][j] = 0;
            } 
        }
        
        int max = 0;

        for (int i = 1; i < m+1. i++)
        {for
            (int j = 1; j < N+1; J +)
            {
            	if (a[i-1]==b[j-1])
            	{
        			mat RIX[I][J] = 1 + matrix[i-1][j-1];
        			max = max > Matrix[i][j]? MAX:MATRIX[I][J];
            	}
            	else
                	matrix[i][j] = 0;
            }}
        
        return max;
    }
;

The above code can meet the requirements of the topic. Also note that we omit part of the code for "Memory recycling" in the above implementation. Of course, because in order to demonstrate the routines of "dynamic planning," here is a very simple implementation, and to optimize it, you can also improve it to achieve higher efficiency.


Similar to the above topic, there are #72 questions (Edit Distance). The topic is to calculate the editing distance between two words, which is described as follows:


This topic is similar to the previous topic, but it is much more complicated. The topic itself can be solved directly using the famous Dreman-Winsch (Needleman-wunsch) algorithm. Needleman-wunsch algorithm is also one of the earliest algorithms in the history of the application of dynamic programming idea design. More about the algorithm, readers can refer to the "Beauty of the algorithm (hidden in the principles behind the data structure)," the 3rd chapter of the book, no longer repeat.


It should be explained that in the specific use of the Needleman-wunsch algorithm, the various editing operations to assign a different score, and this value can be defined by the user. The requirement of this Leetcode topic has already indicated that inserts, deletes, and replacements correspond to 1 steps (so it can be quantified to 1 points). This is different from the numerical value set in the book as an example. Here we give the final implementation code:

Class Solution {public:int mindistance (string word1, String word2) {int m = word1.size (); 

        int n = word2.size ();
        if (m==0) return n;

        if (n==0) return m;  
        
        int * * Matrix = new Int*[m+1];
        int i = 0;
        int j = 0;
        int p = 0;

        int q = 0;
            for (i = 0; i < m+1 i++) {Matrix[i] = new int[n+1]; 
        Matrix[i][0] = 0+i;  
        for (j = 0; J < n+1 J + +) {Matrix[0][j] = 0+j;  

            	for (i = 1; i < m+1. i++) {for (j = 1; j < N+1; J +) { p = matrix[i][j-1] + 1 < matrix[i-1][j] + 1?

                MATRIX[I][J-1] + 1:matrix[i-1][j] + 1;  
                if (Word1[i-1]==word2[j-1]) {q = matrix[i-1][j-1];   
                else {q = matrix[i-1][j-1] + 1;} Matrix[i][j] = p < Q? 
            P:q; 
         
    } return Matrix[m][n]; }
};
Again, we omitted some of the code for "Memory recycling" in the above implementation.



(end of this article)


List of leetcode topics already discussed in this blog
two dynamic programming topics in Leetcode (#62, #63) dynamic Programming topics in Leetcode (2) (#64) Dynamic programming Problem solving in Leetcode (3) (#72, #718) max Continuous subsequence and problem (#53) See if you really mastered binary Search (#35) zigzag arrangement problem and analysis of classic written interview (#6) the problem of bracket matching and the analysis of classic written interview questions (#20, #32) Newton iterative method and a classical programming problem (#69) Three tricky Leetcode interview topic analysis (#48, #169, #231) Leetcode topic resolution on hashing (#187, #389) Yang Hui's triangle and a classic written interview topic (#118, #119) Polish expression (Reverse Polish notation) (#150)

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.