mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-19 20:55:57 +08:00
deploy
This commit is contained in:
@ -3448,7 +3448,7 @@
|
||||
|
||||
|
||||
<h1 id="141">14.1 初探动态规划<a class="headerlink" href="#141" title="Permanent link">¶</a></h1>
|
||||
<p>「动态规划 Dynamic Programming」是一个重要的算法范式,它将一个问题分解为一系列更小的子问题,并通过存储子问题的解来避免重复计算,从而大幅提升时间效率。</p>
|
||||
<p>「动态规划 dynamic programming」是一个重要的算法范式,它将一个问题分解为一系列更小的子问题,并通过存储子问题的解来避免重复计算,从而大幅提升时间效率。</p>
|
||||
<p>在本节中,我们从一个经典例题入手,先给出它的暴力回溯解法,观察其中包含的重叠子问题,再逐步导出更高效的动态规划解法。</p>
|
||||
<div class="admonition question">
|
||||
<p class="admonition-title">爬楼梯</p>
|
||||
@ -3997,7 +3997,7 @@ dp[i] = dp[i-1] + dp[i-2]
|
||||
<p><img alt="爬楼梯对应递归树" src="../intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.png" /></p>
|
||||
<p align="center"> 图:爬楼梯对应递归树 </p>
|
||||
|
||||
<p>观察上图发现,<strong>指数阶的时间复杂度是由于「重叠子问题」导致的</strong>。例如:<span class="arithmatex">\(dp[9]\)</span> 被分解为 <span class="arithmatex">\(dp[8]\)</span> 和 <span class="arithmatex">\(dp[7]\)</span> ,<span class="arithmatex">\(dp[8]\)</span> 被分解为 <span class="arithmatex">\(dp[7]\)</span> 和 <span class="arithmatex">\(dp[6]\)</span> ,两者都包含子问题 <span class="arithmatex">\(dp[7]\)</span> 。</p>
|
||||
<p>观察上图发现,<strong>指数阶的时间复杂度是由于“重叠子问题”导致的</strong>。例如:<span class="arithmatex">\(dp[9]\)</span> 被分解为 <span class="arithmatex">\(dp[8]\)</span> 和 <span class="arithmatex">\(dp[7]\)</span> ,<span class="arithmatex">\(dp[8]\)</span> 被分解为 <span class="arithmatex">\(dp[7]\)</span> 和 <span class="arithmatex">\(dp[6]\)</span> ,两者都包含子问题 <span class="arithmatex">\(dp[7]\)</span> 。</p>
|
||||
<p>以此类推,子问题中包含更小的重叠子问题,子子孙孙无穷尽也。绝大部分计算资源都浪费在这些重叠的问题上。</p>
|
||||
<h2 id="1412">14.1.2 方法二:记忆化搜索<a class="headerlink" href="#1412" title="Permanent link">¶</a></h2>
|
||||
<p>为了提升算法效率,<strong>我们希望所有的重叠子问题都只被计算一次</strong>。为此,我们声明一个数组 <code>mem</code> 来记录每个子问题的解,并在搜索过程中这样做:</p>
|
||||
|
Reference in New Issue
Block a user