@@ -39,4 +39,49 @@ class Solution:
3939 ans = dfs(len (source) - 1 , len (pattern) - 1 )
4040 dfs.cache_clear()
4141 return ans
42+ ```
43+
44+ ## 2. 转化为递推
45+
46+ 状态定义: ` f[i][j] ` 表示考虑原字符串前 $i$ 个字符和模式串前 $j$ 个字符时,能够删除的最大次数。
47+
48+ 状态转移:
49+
50+ - 如果 $i < j$,说明原字符串剩余长度小于模式串剩余长度,无法匹配,返回负无穷
51+ - 如果 $i < 0$,说明原字符串已经处理完,返回 0
52+ - 如果 $j < 0$ 或当前字符不匹配,只能删除当前字符(如果它在目标索引中)
53+ - 如果当前字符匹配,可以选择匹配或删除当前字符,取两种情况的最大值
54+
55+ 边界条件:
56+ - 如果 $i < 0$ 且 $j < 0$,说明原字符串和模式串都处理完,返回 0
57+ - 如果 $i < 0$ 且 $j \geq 0$,说明原字符串已经处理完,返回 0
58+ - 如果 $i \geq 0$ 且 $j < 0$,说明模式串已经处理完,返回 0
59+ - 如果 $i \geq 0$ 且 $j \geq 0$ 且当前字符不匹配,只能删除当前字符(如果它在目标索引中)
60+ - 如果 $i \geq 0$ 且 $j \geq 0$ 且当前字符匹配,可以选择匹配或删除当前字符,取两种情况的最大值
61+
62+ 最终答案: ` f[len(source)][len(pattern)] ` 。
63+
64+ 复杂度分析:
65+
66+ - 时间复杂度: $O(n \times m)$
67+ - 空间复杂度: $O(n \times m)$
68+
69+ ** Python3**
70+
71+ ``` python
72+ class Solution :
73+ def maxRemovals (self , s : str , t : str , targetIndices : List[int ]) -> int :
74+ targetIndices = set (targetIndices)
75+ n, m = len (s), len (t)
76+ f = [[- inf] * (m + 1 ) for _ in range (n + 1 )]
77+ f[0 ][0 ] = 0
78+
79+ for i in range (n):
80+ is_del = int (i in targetIndices)
81+ f[i + 1 ][0 ] = f[i][0 ] + is_del
82+ for j in range (min (i + 1 , m)):
83+ f[i + 1 ][j + 1 ] = f[i][j + 1 ] + is_del
84+ if s[i] == t[j]:
85+ f[i + 1 ][j + 1 ] = max (f[i + 1 ][j + 1 ], f[i][j])
86+ return f[n][m]
4287```
0 commit comments