Dynamic programming to solve the problem: edit distance and decoding method

Dynamic programming algorithm to solve a lot of the magic weapon of choice.
Thought it can be summarized as: The previous state values to determine the current state value.
Therefore, in this type of subject, the focus is to find a link on the current state and the state .
Specific theory is not pulled, or directly on a pair of title

Edit distance

This question is a difficult question on leetcode.
Here Insert Picture Description
At first glance the subject may feel unable to start, because word1 and word2 is difficult to see the connection from the visual point of view.
So, we tried to use dynamic programming to find the link between the state
we let D [i] [j] represents ago i bits of the first string and the first j bits of the second string edit distance between.
For chestnut, for example 2, D [9] [9 ] is represented by the string edit distance between word1 and word2, we require is this.
After that, the focus here, how do we find D [i] [j] it? After analysis, there are three ways to update.

  • I before the bit string into a second string before the j-1 position, then the second j-th bit string insert (edit distance of D [i] [j- 1] +1)
  • I-1 before the bit string into a second string of the first j bits, then the first bit i of the string deleted (bit edit distance D [i-1] [j ] +1)
  • I-1 before the bit string into a second string before the j-1 position, and then replace the i-th bit characters. If the first character of the first bit i of the string and a second string of j bits of the same, without replacing the (edit distance D [i-1] [j-1]); the other hand, if not identical, needs to be replaced (edit distance D [i-1] [j-1] +1)

After analysis, it is not much clearer?
That is, we require D [i] [j], only in D [i] [j-1 ] + 1, D [i-1] [j] + 1, D [i-1] [j- 1] (or D [i-1] [j -1]) select a minimum on the line.
Obviously, D [0] [j] = j, D [i] [0] = i ( becomes a null string from a bit string needs to be inserted i i-th character)
Thus, to obtain a result, i.e. step by step through iteration can. code show as below:

class Solution:
    def minDistance(self, word1, word2):
        len1 = len(word1)
        len2 = len(word2)
        # 若两个串中有一个为0串,则返回另一个串的长度
        if len1*len2 == 0:       
            return len1 + len2
        dp = [[0]*(len2+1) for _ in range(len1+1)]
        for i in range(len1+1):
            dp[i][0] = i
        for j in range(len2+1):
            dp[0][j] = j
        for i in range(1, len1+1):
            for j in range(1, len2+1):
                # 分别对应三种情况
                tog = dp[i-1][j-1]
                rep_1 = dp[i-1][j] + 1
                rep_2 = dp[i][j-1] + 1
                if word1[i-1] != word2[j-1]:
                    tog += 1
                dp[i][j] = min(tog, rep_1, rep_2)
        return dp[len1][len2]

.

Decoding method

This question is a moderate problem on leetcode.
Here Insert Picture Description
This question looks slightly touches - violence through each element method, and then one by one is determined. But think about it is a little complicated (those months if else yo ...)
But now we have a secret weapon, dynamic programming!
The old rules, to explore the relationship between the two states.

We let D [i] denotes the string before the i-th character decoding method of the total. So, update D [i] There are the following cases:

  • This firstiBit is '0': 1 , i-1 if the first bit is a '1' or '2', the case for the i-bits only for the first decoding mode bit i-1 and i-th bit combination (alone '0' can not be decoded). At this time, D [i] = D [i-2]; 2 , i-1 if the first bit of the other elements, the string can not be decoded (bit i at this time can not be decoded either element alone, and not the i joint decoding -1-site element. At this time D [i] = 0
  • This firsti-1Bit is '1': In this case the i-th bit element may be decoded (D [i-1]) alone, and the joint i-1 position decoder element (D [i-2] Thus D [i]. = D [i-1] + D [i-2]
  • This firsti-1Bit is '2': 1 , when the i-th bit element between '1' and '6', and the second case, as may be decoded independently, may be jointly decoded. D [i] = D [i-1] + D [i-2]; 2 , if the i-th bit element for other elements, and not the first i-1 site element joint decoding it, can only be decoded independently. At this time, D [i] = D [i -1]

You may be wondering why there will be 1.1 D [i] = D [i-2], this is because the first i-1 elements and only the i-th element binding decoding, and if so, had the i binding elements of -2 i-1 elements (if any) does not exist.

Haha, although a bit cumbersome, but we finally put all states are analyzed out.
Further, since the process involves only the D [I], D [I-. 1], D [I-2] , so we can use the three constants to dynamically represent these values (rather than maintained the array D), thus saving space.

class Solution:
    def numDecodings(self, s: str) -> int:
        if s[0] == "0":
            return 0
        curr, pre, tmp = 1, 1, 1
        len_s = len(s)
        for i in range(1, len_s):
        # temp表示D[i-1]
        # curr表示D[i]
        # pre 表示D[i-2]
            temp = curr   
            if s[i] == '0':
                if s[i-1] == '1' or s[i-1] == '2':
                    curr = pre
                else:
                    return 0
            elif s[i-1] == '1' or (s[i-1]=='2' and s[i] >= '1' and s[i] <='6'):
                curr += pre
            pre = temp
        return curr
Published 19 original articles · won praise 1 · views 710

Guess you like

Origin blog.csdn.net/weixin_43901558/article/details/104827120