mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-05 03:30:30 +08:00
deploy
This commit is contained in:
@@ -3428,13 +3428,13 @@
|
||||
</div>
|
||||
<p>如下图所示,将 <code>kitten</code> 转换为 <code>sitting</code> 需要编辑 3 步,包括 2 次替换操作与 1 次添加操作;将 <code>hello</code> 转换为 <code>algo</code> 需要 3 步,包括 2 次替换操作和 1 次删除操作。</p>
|
||||
<p><img alt="编辑距离的示例数据" src="../edit_distance_problem.assets/edit_distance_example.png" /></p>
|
||||
<p align="center"> Fig. 编辑距离的示例数据 </p>
|
||||
<p align="center"> 图:编辑距离的示例数据 </p>
|
||||
|
||||
<p><strong>编辑距离问题可以很自然地用决策树模型来解释</strong>。字符串对应树节点,一轮决策(一次编辑操作)对应树的一条边。</p>
|
||||
<p>如下图所示,在不限制操作的情况下,每个节点都可以派生出许多条边,每条边对应一种操作,这意味着从 <code>hello</code> 转换到 <code>algo</code> 有许多种可能的路径。</p>
|
||||
<p>从决策树的角度看,本题的目标是求解节点 <code>hello</code> 和节点 <code>algo</code> 之间的最短路径。</p>
|
||||
<p><img alt="基于决策树模型表示编辑距离问题" src="../edit_distance_problem.assets/edit_distance_decision_tree.png" /></p>
|
||||
<p align="center"> Fig. 基于决策树模型表示编辑距离问题 </p>
|
||||
<p align="center"> 图:基于决策树模型表示编辑距离问题 </p>
|
||||
|
||||
<p><strong>第一步:思考每轮的决策,定义状态,从而得到 <span class="arithmatex">\(dp\)</span> 表</strong></p>
|
||||
<p>每一轮的决策是对字符串 <span class="arithmatex">\(s\)</span> 进行一次编辑操作。</p>
|
||||
@@ -3454,7 +3454,7 @@
|
||||
<li>将 <span class="arithmatex">\(s[i-1]\)</span> 替换为 <span class="arithmatex">\(t[j-1]\)</span> ,则剩余子问题 <span class="arithmatex">\(dp[i-1, j-1]\)</span> 。</li>
|
||||
</ol>
|
||||
<p><img alt="编辑距离的状态转移" src="../edit_distance_problem.assets/edit_distance_state_transfer.png" /></p>
|
||||
<p align="center"> Fig. 编辑距离的状态转移 </p>
|
||||
<p align="center"> 图:编辑距离的状态转移 </p>
|
||||
|
||||
<p>根据以上分析,可得最优子结构:<span class="arithmatex">\(dp[i, j]\)</span> 的最少编辑步数等于 <span class="arithmatex">\(dp[i, j-1]\)</span> , <span class="arithmatex">\(dp[i-1, j]\)</span> , <span class="arithmatex">\(dp[i-1, j-1]\)</span> 三者中的最少编辑步数,再加上本次的编辑步数 <span class="arithmatex">\(1\)</span> 。对应的状态转移方程为:</p>
|
||||
<div class="arithmatex">\[
|
||||
@@ -3786,6 +3786,8 @@ dp[i, j] = dp[i-1, j-1]
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p align="center"> 图:编辑距离的动态规划过程 </p>
|
||||
|
||||
<h3 id="_2">状态压缩<a class="headerlink" href="#_2" title="Permanent link">¶</a></h3>
|
||||
<p>由于 <span class="arithmatex">\(dp[i,j]\)</span> 是由上方 <span class="arithmatex">\(dp[i-1, j]\)</span> 、左方 <span class="arithmatex">\(dp[i, j-1]\)</span> 、左上方状态 <span class="arithmatex">\(dp[i-1, j-1]\)</span> 转移而来,而正序遍历会丢失左上方 <span class="arithmatex">\(dp[i-1, j-1]\)</span> ,倒序遍历无法提前构建 <span class="arithmatex">\(dp[i, j-1]\)</span> ,因此两种遍历顺序都不可取。</p>
|
||||
<p>为此,我们可以使用一个变量 <code>leftup</code> 来暂存左上方的解 <span class="arithmatex">\(dp[i-1, j-1]\)</span> ,从而只需考虑左方和上方的解。此时的情况与完全背包问题相同,可使用正序遍历。</p>
|
||||
|
||||
Reference in New Issue
Block a user