Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

583.两个字符串的删除操作增加Go动态规划二解法 #2805

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion problems/0583.两个字符串的删除操作.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

dp[i][j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数。

这里dp数组的定义有点点绕,大家要撸清思路
这里dp数组的定义有点点绕,大家要理清思路

2. 确定递推公式

Expand Down Expand Up @@ -255,6 +255,8 @@ class Solution(object):
```
### Go:

动态规划一

```go
func minDistance(word1 string, word2 string) int {
dp := make([][]int, len(word1)+1)
Expand Down Expand Up @@ -287,6 +289,35 @@ 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
Expand Down