File tree Expand file tree Collapse file tree 1 file changed +35
-1
lines changed Expand file tree Collapse file tree 1 file changed +35
-1
lines changed Original file line number Diff line number Diff line change 3333
3434dp[ i] [ j ] :以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数。
3535
36- 这里dp数组的定义有点点绕,大家要撸清思路 。
36+ 这里dp数组的定义有点点绕,大家要理清思路 。
3737
38382 . 确定递推公式
3939
@@ -255,6 +255,8 @@ class Solution(object):
255255```
256256### Go:
257257
258+ 动态规划一
259+
258260```go
259261func minDistance(word1 string, word2 string) int {
260262 dp := make([][]int, len(word1)+1)
@@ -287,8 +289,40 @@ func min(a, b int) int {
287289 return b
288290}
289291```
292+
293+
294+ 动态规划二
295+
296+ ``` go
297+ func minDistance (word1 string , word2 string ) int {
298+ dp := make ([][]int , len (word1) + 1 )
299+ for i := range dp {
300+ dp[i] = make ([]int , len (word2) + 1 )
301+ }
302+ for i := 1 ; i <= len (word1); i++ {
303+ for j := 1 ; j <= len (word2); j++ {
304+ if word1[i-1 ] == word2[j-1 ] {
305+ dp[i][j] = dp[i-1 ][j-1 ] + 1
306+ } else {
307+ dp[i][j] = max (dp[i-1 ][j], dp[i][j-1 ])
308+ }
309+ }
310+ }
311+ return len (word1) + len (word2) - dp[len (word1)][len (word2)] * 2
312+ }
313+
314+ func max (x , y int ) int {
315+ if x > y {
316+ return x
317+ }
318+ return y
319+ }
320+ ```
321+
322+
290323### JavaScript:
291324
325+
292326``` javascript
293327// 方法一
294328var minDistance = (word1 , word2 ) => {
You can’t perform that action at this time.
0 commit comments