K Edit Distance
Given a set of strings which just has lower case letters and a target string, output all the strings for each the edit distance with the target no greater thank.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example
Given words =["abc", "abd", "abcd", "adc"]and target ="ac", k =1
Return["abc", "adc"]
Note
暴力做法就是target和words一个个进行比较
优化做法,我们使用Trie加DFS加DP
Trie存所有词
DFS遍历Trie树上的所有a-z的节点
dp[i] 表示从Trie的root节点走到当前node节点,形成的Prefix和 target的前i个字符的最小编辑距离
dp指的是上一次的情况。现在更新i,j这个格子,那么我要往左上方看(i-1, j-1),要往上看(i-1, j),这两种就是分别对应dp数组里的dp[j-1]和dp[j]。然后我还要往左边看i, j-1,此时行不变,相当于我看next数组里我左边那个刚刚更新过的值,所以是next[j-1]. dp代表这一行 ====> [i-1,j-1],[i -1,j] next代表dp的下一行 [i,j-1], [i,j]. next[0] = dp[0] + 1 相当于next[0] = i, i 从1开始累积
dp[i][j] = dp[i-1][j-1]
next[i] = dp[i-1]
=======
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
next[i] = min(dp[i-1], dp[i], next[i-1])Code
Last updated