File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 18
18
19
19
## 思路
20
20
21
+ ### 动态规划一
22
+
21
23
本题和[ 动态规划:115.不同的子序列] ( https://programmercarl.com/0115.不同的子序列.html ) 相比,其实就是两个字符串都可以删除了,情况虽说复杂一些,但整体思路是不变的。
22
24
23
25
这次是两个字符串可以相互删了,这种题目也知道用动态规划的思路来解,动规五部曲,分析如下:
@@ -98,6 +100,29 @@ public:
98
100
99
101
```
100
102
103
+ ### 动态规划二
104
+
105
+ 本题和[ 动态规划:1143.最长公共子序列] ( https://programmercarl.com/1143.最长公共子序列.html ) 基本相同,只要求出两个字符串的最长公共子序列长度即可,那么除了最长公共子序列之外的字符都是必须删除的,最后用两个字符串的总长度减去两个最长公共子序列的长度就是删除的最少步数。
106
+
107
+ 代码如下:
108
+
109
+ ``` CPP
110
+ class Solution {
111
+ public:
112
+ int minDistance(string word1, string word2) {
113
+ vector<vector<int >> dp(word1.size()+1, vector<int >(word2.size()+1, 0));
114
+ for (int i=1; i<=word1.size(); i++){
115
+ for (int j=1; j<=word2.size(); j++){
116
+ if (word1[ i-1] == word2[ j-1] ) dp[ i] [ j ] = dp[ i-1] [ j-1 ] + 1;
117
+ else dp[ i] [ j ] = max(dp[ i-1] [ j ] , dp[ i] [ j-1 ] );
118
+ }
119
+ }
120
+ return word1.size()+word2.size()-dp[ word1.size()] [ word2.size() ] * 2;
121
+ }
122
+ };
123
+
124
+ ```
125
+
101
126
## 其他语言版本
102
127
103
128
You can’t perform that action at this time.
0 commit comments