mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-05 22:59:31 +08:00
Merge pull request #2805 from markwang1992/583-minDistance
583.两个字符串的删除操作增加Go动态规划二解法
This commit is contained in:
@ -33,7 +33,7 @@
|
||||
|
||||
dp[i][j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数。
|
||||
|
||||
这里dp数组的定义有点点绕,大家要撸清思路。
|
||||
这里dp数组的定义有点点绕,大家要理清思路。
|
||||
|
||||
2. 确定递推公式
|
||||
|
||||
@ -255,6 +255,8 @@ class Solution(object):
|
||||
```
|
||||
### Go:
|
||||
|
||||
动态规划一
|
||||
|
||||
```go
|
||||
func minDistance(word1 string, word2 string) int {
|
||||
dp := make([][]int, len(word1)+1)
|
||||
@ -287,8 +289,40 @@ func min(a, b int) int {
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
动态规划二
|
||||
|
||||
```go
|
||||
func minDistance(word1 string, word2 string) int {
|
||||
dp := make([][]int, len(word1) + 1)
|
||||
for i := range dp {
|
||||
dp[i] = make([]int, len(word2) + 1)
|
||||
}
|
||||
for i := 1; i <= len(word1); i++ {
|
||||
for j := 1; j <= len(word2); j++ {
|
||||
if word1[i-1] == word2[j-1] {
|
||||
dp[i][j] = dp[i-1][j-1] + 1
|
||||
} else {
|
||||
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return len(word1) + len(word2) - dp[len(word1)][len(word2)] * 2
|
||||
}
|
||||
|
||||
func max(x, y int) int {
|
||||
if x > y {
|
||||
return x
|
||||
}
|
||||
return y
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### JavaScript:
|
||||
|
||||
|
||||
```javascript
|
||||
// 方法一
|
||||
var minDistance = (word1, word2) => {
|
||||
|
Reference in New Issue
Block a user