Source of question: "waiting for words", original @ Chen liren. You are welcome to continue to pay attention to the Public Account "" waiting for words"
If the original question is given a string, you can insert a character to make it a return text. Calculates the minimum number of characters inserted. For example:
1. AB is inserted with at least 1 character, and * B * ab2. AA is inserted with at least 0 characters. 3. ABCD is inserted with at least 3 characters, and * DCB * ABCD
Analysis: according to the definition of the return string, it is easy to get a recursive idea. First, compare the first and last characters. If the number is equal, the number of inserts equals to the number of inserts in the middle, you can add a character at the beginning or the end to make the two ends equal. For example, ABCD can be converted to abcda or dabcd. In this way, the recursive equation is: when STR [I] = STR [J], fun (I, j) = fun (I + 1, J-1); otherwise fun (I, j) = min (fun (I + 1, J), fun (I, J-1) + 1. it is easy to see that this recursion has a repeated subsequence, and the topic requires the shortest, so it has the optimal meaning, so it can be converted to dynamic planning. The transfer equation of dynamic planning is generally the same as that of recursive equations, only the previous results must be used for solving the problem. In this question, we can see that the solution direction is from the two ends to the internal, just like the judgment of the return string. The idea of dynamic planning is to first find Len = 1, then Len = 2, then ......, The following code is available:
Int mininsertchar (char * SRC) {If (src = NULL) Return-1; int length = strlen (SRC); int I, Len; int ** dp = new int * [Length + 1]; for (I = 0; I <= length; I ++) {DP [I] = new int [Length + 1]; memset (DP [I], 0, sizeof (INT) * (Length + 1 ));} for (LEN = 1; Len <length; Len ++) // The length ranges from 1 to length-1 {for (I = length-len; I> = 1; I --) // forward from the back {Int J = I + Len; If (SRC [I-1] = SRC [J-1]) DP [I] [J] = DP [I + 1] [J-1]; else DP [I] [J] = min (DP [I + 1] [J], DP [I] [J-1]) + 1 ;}int res = DP [1] [length]; for (I = 0; I <= length; I ++) delete [] DP [I]; Delete [] DP; return res ;}
This Code only represents my opinion. If you have any mistakes, please correct them. Thank you.