File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change 1818
1919## 思路
2020
21+ ### 动态规划一
22+
2123本题和[ 动态规划:115.不同的子序列] ( https://programmercarl.com/0115.不同的子序列.html ) 相比,其实就是两个字符串都可以删除了,情况虽说复杂一些,但整体思路是不变的。
2224
2325这次是两个字符串可以相互删了,这种题目也知道用动态规划的思路来解,动规五部曲,分析如下:
@@ -98,6 +100,29 @@ public:
98100
99101```
100102
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+
101126## 其他语言版本
102127
103128
Original file line number Diff line number Diff line change @@ -52,7 +52,7 @@ for(int i = 0; i < weight.size(); i++) { // 遍历物品
5252``` CPP
5353// 先遍历物品,再遍历背包
5454for (int i = 0 ; i < weight.size(); i++) { // 遍历物品
55- for(int j = weight[ i] ; j < bagWeight ; j++) { // 遍历背包容量
55+ for(int j = weight[ i] ; j <= bagWeight ; j++) { // 遍历背包容量
5656 dp[ j] = max(dp[ j] , dp[ j - weight[ i]] + value[ i] );
5757
5858 }
You can’t perform that action at this time.
0 commit comments