mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-30 00:04:44 +08:00
Release reviewed gh-pages candidate
This commit is contained in:
@@ -1955,8 +1955,8 @@
|
||||
<p>Given a staircase with <span class="arithmatex">\(n\)</span> steps, you may climb <span class="arithmatex">\(1\)</span> or <span class="arithmatex">\(2\)</span> steps at a time. How many ways are there to reach the top?</p>
|
||||
</div>
|
||||
<p>As shown in Figure 14-1, a staircase with <span class="arithmatex">\(3\)</span> steps has <span class="arithmatex">\(3\)</span> possible ways to reach the top.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.png" data-dark-src="/assets/figure-svg/figures/d0c3d4772f47d8869fd244ea.json" data-src="/assets/figure-svg/figures/4d0f7721647a1c2821cc4b92.json" style=";--figure-ratio:960.0/540.0"><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.svg" data-theme="light" tabindex="-1" type="image/svg+xml">Number of ways to reach step 3</object><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">Number of ways to reach step 3</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-1 Number of ways to reach step 3 </p>
|
||||
<p><ha-svg-figure aria-label="Three ways to climb to the third step" class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.png" data-dark-src="/assets/figure-svg/figures/d0c3d4772f47d8869fd244ea.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/4d0f7721647a1c2821cc4b92.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">Number of ways to reach step 3</object><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_example.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">Number of ways to reach step 3</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-1 Number of ways to reach step 3 </p><div class="ha-sr-only figure-description"><h2>Description of Figure 14-1: Three ways to climb to the third step</h2><p>Three step-by-step paths show the distinct ways to reach step 3.</p><p>Numbering the ground level as 0, each move climbs 1 or 2 steps, with the goal of landing on step 3.</p><p>From left to right, the stairs are numbered 0 through 6, with the tread of target step 3 highlighted in green. Three sets of jump arcs are drawn above the same staircase, matching the step sequences listed below; a caption beneath the staircase notes, "There are 3 ways to reach step 3."</p><p>The solid cyan path advances along steps 0 → 1 → 2 → 3, climbing 1 step three times in a row; the dotted blue path follows 0 → 2 → 3, climbing 2 steps to step 2 and then 1 step to step 3; the dashed orange path follows 0 → 1 → 3, climbing 1 step to step 1 and then 2 steps to step 3. Climbing 2 steps then 1 step visits a different intermediate step from climbing 1 step then 2 steps, so the two count as distinct ways.</p></div>
|
||||
<p>The goal is to count solutions, so <strong>we can use backtracking to enumerate every possibility</strong>. View climbing as a sequence of choices: starting from the ground, choose to climb <span class="arithmatex">\(1\)</span> or <span class="arithmatex">\(2\)</span> steps each time. Add <span class="arithmatex">\(1\)</span> to the count whenever we reach the top, and prune any branch that goes beyond it. The code is as follows:</p>
|
||||
<div class="tabbed-set tabbed-alternate" data-tabs="1:13"><input checked="checked" id="__tabbed_1_1" name="__tabbed_1" type="radio"/><input id="__tabbed_1_2" name="__tabbed_1" type="radio"/><input id="__tabbed_1_3" name="__tabbed_1" type="radio"/><input id="__tabbed_1_4" name="__tabbed_1" type="radio"/><input id="__tabbed_1_5" name="__tabbed_1" type="radio"/><input id="__tabbed_1_6" name="__tabbed_1" type="radio"/><input id="__tabbed_1_7" name="__tabbed_1" type="radio"/><input id="__tabbed_1_8" name="__tabbed_1" type="radio"/><input id="__tabbed_1_9" name="__tabbed_1" type="radio"/><input id="__tabbed_1_10" name="__tabbed_1" type="radio"/><input id="__tabbed_1_11" name="__tabbed_1" type="radio"/><input id="__tabbed_1_12" name="__tabbed_1" type="radio"/><input id="__tabbed_1_13" name="__tabbed_1" type="radio"/><div class="tabbed-labels"><label for="__tabbed_1_1">Python</label><label for="__tabbed_1_2">C++</label><label for="__tabbed_1_3">Java</label><label for="__tabbed_1_4">C#</label><label for="__tabbed_1_5">Go</label><label for="__tabbed_1_6">Swift</label><label for="__tabbed_1_7">JS</label><label for="__tabbed_1_8">TS</label><label for="__tabbed_1_9">Dart</label><label for="__tabbed_1_10">Rust</label><label for="__tabbed_1_11">C</label><label for="__tabbed_1_12">Kotlin</label><label for="__tabbed_1_13">Ruby</label></div>
|
||||
<div class="tabbed-content">
|
||||
@@ -2353,8 +2353,8 @@ dp[i-1], dp[i-2], \dots, dp[2], dp[1]
|
||||
dp[i] = dp[i-1] + dp[i-2]
|
||||
\]</div>
|
||||
<p>Thus, the subproblems are linked by a recurrence: <strong>the solution to the original problem can be constructed from subproblem solutions</strong>. Figure 14-2 illustrates this relationship.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.png" data-dark-src="/assets/figure-svg/figures/5002ac641e808bab77966425.json" data-src="/assets/figure-svg/figures/8715a040b0aed7825a3a871c.json" style=";--figure-ratio:960.0/540.0"><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.svg" data-theme="light" tabindex="-1" type="image/svg+xml">Recurrence for the number of ways</object><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">Recurrence for the number of ways</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-2 Recurrence for the number of ways </p>
|
||||
<p><ha-svg-figure aria-label="Counting ways to reach step 5 from the counts for steps 3 and 4" class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.png" data-dark-src="/assets/figure-svg/figures/5002ac641e808bab77966425.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/8715a040b0aed7825a3a871c.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">Recurrence for the number of ways</object><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_state_transfer.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">Recurrence for the number of ways</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-2 Recurrence for the number of ways </p><div class="ha-sr-only figure-description"><h3>Description of Figure 14-2: Counting ways to reach step 5 from the counts for steps 3 and 4</h3><p>The final move onto step 5 must come from either step 3 or step 4, giving 3 + 5 = 8 ways.</p><p>Because each move climbs only 1 or 2 steps, let dp[n] be the number of ways to reach step n, with initial states dp[1] = 1 and dp[2] = 2.</p><p>Steps 3, 4, and 5 on the staircase are highlighted in green, cyan, and blue, respectively. First, 3 dashed green arcs converge on step 3 (labeled dp[3] = 3) and 5 solid cyan arcs converge on step 4 (labeled dp[4] = 5); from there, a single dashed green arc spanning 2 steps and a single solid cyan arc spanning 1 step converge on step 5. The equation dp[5] = dp[3] + dp[4] = 8 appears at the top, and a row at the bottom pairs steps 1 through 6 with their numbers of ways.</p><table><caption>Steps and numbers of ways shown in the figure</caption><thead><tr><th scope="col">Number of steps n</th><th scope="col">Number of ways dp[n]</th></tr></thead><tbody><tr><th scope="row">1</th><td>1</td></tr><tr><th scope="row">2</th><td>2</td></tr><tr><th scope="row">3</th><td>3</td></tr><tr><th scope="row">4</th><td>5</td></tr><tr><th scope="row">5</th><td>8</td></tr><tr><th scope="row">6</th><td>13</td></tr></tbody></table><p>To reach step 5, the final move either jumps 2 steps up from step 3 or jumps 1 step up from step 4. Extending each of the 3 ways to reach step 3 with a 2-step jump produces 3 ways to reach step 5; extending each of the 5 ways to reach step 4 with a 1-step jump produces another 5 ways. Because these two groups differ in the step preceding the final move, they are mutually exclusive and collectively exhaustive, so dp[5] = dp[3] + dp[4] = 3 + 5 = 8. More generally, for any step i (i ≥ 3), dp[i] = dp[i-1] + dp[i-2].</p></div>
|
||||
<p>The recurrence gives a brute-force search solution. Starting at <span class="arithmatex">\(dp[n]\)</span>, <strong>recursively express a larger problem as the sum of two smaller ones</strong> until reaching <span class="arithmatex">\(dp[1]\)</span> or <span class="arithmatex">\(dp[2]\)</span>. Their solutions are known: <span class="arithmatex">\(dp[1] = 1\)</span> and <span class="arithmatex">\(dp[2] = 2\)</span>, meaning steps <span class="arithmatex">\(1\)</span> and <span class="arithmatex">\(2\)</span> can be reached in <span class="arithmatex">\(1\)</span> and <span class="arithmatex">\(2\)</span> ways, respectively.</p>
|
||||
<p>Like the standard backtracking code, the following code performs depth-first search, but is more concise:</p>
|
||||
<div class="tabbed-set tabbed-alternate" data-tabs="2:13"><input checked="checked" id="__tabbed_2_1" name="__tabbed_2" type="radio"/><input id="__tabbed_2_2" name="__tabbed_2" type="radio"/><input id="__tabbed_2_3" name="__tabbed_2" type="radio"/><input id="__tabbed_2_4" name="__tabbed_2" type="radio"/><input id="__tabbed_2_5" name="__tabbed_2" type="radio"/><input id="__tabbed_2_6" name="__tabbed_2" type="radio"/><input id="__tabbed_2_7" name="__tabbed_2" type="radio"/><input id="__tabbed_2_8" name="__tabbed_2" type="radio"/><input id="__tabbed_2_9" name="__tabbed_2" type="radio"/><input id="__tabbed_2_10" name="__tabbed_2" type="radio"/><input id="__tabbed_2_11" name="__tabbed_2" type="radio"/><input id="__tabbed_2_12" name="__tabbed_2" type="radio"/><input id="__tabbed_2_13" name="__tabbed_2" type="radio"/><div class="tabbed-labels"><label for="__tabbed_2_1">Python</label><label for="__tabbed_2_2">C++</label><label for="__tabbed_2_3">Java</label><label for="__tabbed_2_4">C#</label><label for="__tabbed_2_5">Go</label><label for="__tabbed_2_6">Swift</label><label for="__tabbed_2_7">JS</label><label for="__tabbed_2_8">TS</label><label for="__tabbed_2_9">Dart</label><label for="__tabbed_2_10">Rust</label><label for="__tabbed_2_11">C</label><label for="__tabbed_2_12">Kotlin</label><label for="__tabbed_2_13">Ruby</label></div>
|
||||
@@ -2583,8 +2583,8 @@ dp[i] = dp[i-1] + dp[i-2]
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20dfs%28i%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22Search%22%22%22%0A%20%20%20%20%23%20The%20values%20of%20dp%5B1%5D%20and%20dp%5B2%5D%20are%20known%3B%20return%20the%20corresponding%20value%0A%20%20%20%20if%20i%20%3D%3D%201%20or%20i%20%3D%3D%202%3A%0A%20%20%20%20%20%20%20%20return%20i%0A%20%20%20%20%23%20dp%5Bi%5D%20%3D%20dp%5Bi-1%5D%20%2B%20dp%5Bi-2%5D%0A%20%20%20%20count%20%3D%20dfs%28i%20-%201%29%20%2B%20dfs%28i%20-%202%29%0A%20%20%20%20return%20count%0A%0A%0Adef%20climbing_stairs_dfs%28n%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22Climbing%20stairs%3A%20search%22%22%22%0A%20%20%20%20return%20dfs%28n%29%0A%0A%0A%22%22%22Driver%20code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20n%20%3D%209%0A%0A%20%20%20%20res%20%3D%20climbing_stairs_dfs%28n%29%0A%20%20%20%20print%28f%22Number%20of%20ways%20to%20climb%20%7Bn%7D%20stairs%3A%20%7Bres%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" rel="noopener noreferrer" target="_blank">View full screen ></a></div></p>
|
||||
</details>
|
||||
<p>Figure 14-3 shows the recursion tree for brute-force search. For <span class="arithmatex">\(dp[n]\)</span>, its depth is <span class="arithmatex">\(n\)</span>, and the time complexity is <span class="arithmatex">\(O(2^n)\)</span>. Exponential growth is explosive, so a relatively large <span class="arithmatex">\(n\)</span> leads to a very long wait.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.png" data-dark-src="/assets/figure-svg/figures/6cdd7dadd8db29e08bfb8ba2.json" data-src="/assets/figure-svg/figures/851c562e8064b749fd96f3cb.json" style=";--figure-ratio:960.0/540.0"><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.svg" data-theme="light" tabindex="-1" type="image/svg+xml">Recursion tree for climbing stairs</object><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">Recursion tree for climbing stairs</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-3 Recursion tree for climbing stairs </p>
|
||||
<p><ha-svg-figure aria-label="Overlapping subproblems in brute-force climbing stairs search" class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.png" data-dark-src="/assets/figure-svg/figures/6cdd7dadd8db29e08bfb8ba2.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/851c562e8064b749fd96f3cb.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">Recursion tree for climbing stairs</object><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_tree.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">Recursion tree for climbing stairs</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-3 Recursion tree for climbing stairs </p><div class="ha-sr-only figure-description"><h3>Description of Figure 14-3: Overlapping subproblems in brute-force climbing stairs search</h3><p>When brute-force recursion splits top-down from dp[9], identical subproblems do not share results and are repeatedly expanded across different branches.</p><p>In the climbing stairs problem, each move climbs 1 or 2 steps, and dp[i] denotes the number of ways to reach step i. Brute-force search recursively decomposes each state using dp[i] = dp[i - 1] + dp[i - 2] until reaching the base cases dp[1] = 1 or dp[2] = 2.</p><p>Computing dp[9] requires dp[8] and dp[7], and computing dp[8] again requires dp[7] and dp[6]. The two occurrences of dp[7] in the brute-force tree do not share a single computation; each occurrence is expanded and solved all over again.</p><p>The figure draws only the first four levels, with 15 state nodes in total, and 16 ellipses along the bottom indicating continued recursion down to the base cases dp[1] or dp[2]. Counts in the table (such as dp[5] appearing 4 times) cover only the four drawn levels, not the full recursion.</p><p>The tables below first list the four drawn levels and then summarize by state. Left and right subproblems in the decomposition table follow the recurrence; the children of every level-4 node are shown only as ellipses in the figure rather than drawn individually. In particular, dp[4] and dp[3] appear only on level 4, so their subproblems in those two rows come from the recurrence and are not drawn in the figure.</p><table><caption>Recursive states across the four levels shown</caption><thead><tr><th scope="col">Level (root is level 1)</th><th scope="col">States (left to right)</th></tr></thead><tbody><tr><th scope="row">1</th><td>dp[9]</td></tr><tr><th scope="row">2</th><td>dp[8], dp[7]</td></tr><tr><th scope="row">3</th><td>dp[7], dp[6], dp[6], dp[5]</td></tr><tr><th scope="row">4</th><td>dp[6], dp[5], dp[5], dp[4], dp[5], dp[4], dp[4], dp[3]</td></tr></tbody></table><table><caption>Decomposition and occurrence counts in the first four levels</caption><thead><tr><th scope="col">State</th><th scope="col">Left subproblem</th><th scope="col">Right subproblem</th><th scope="col">Count in first four levels</th></tr></thead><tbody><tr><th scope="row">dp[9]</th><td>dp[8]</td><td>dp[7]</td><td>1</td></tr><tr><th scope="row">dp[8]</th><td>dp[7]</td><td>dp[6]</td><td>1</td></tr><tr><th scope="row">dp[7]</th><td>dp[6]</td><td>dp[5]</td><td>2</td></tr><tr><th scope="row">dp[6]</th><td>dp[5]</td><td>dp[4]</td><td>3</td></tr><tr><th scope="row">dp[5]</th><td>dp[4]</td><td>dp[3]</td><td>4</td></tr><tr><th scope="row">dp[4]</th><td>dp[3]</td><td>dp[2]</td><td>3</td></tr><tr><th scope="row">dp[3]</th><td>dp[2]</td><td>dp[1]</td><td>1</td></tr></tbody></table><p>The caption at the bottom of the figure connects overlapping subproblems to exponential runtime: brute-force recursion repeatedly solves the same states, resulting in an O(2ⁿ) time bound, where 2ⁿ means 2 to the power n.</p></div>
|
||||
<p>As Figure 14-3 shows, <strong>overlapping subproblems cause the exponential time complexity</strong>. For example, <span class="arithmatex">\(dp[9]\)</span> splits into <span class="arithmatex">\(dp[8]\)</span> and <span class="arithmatex">\(dp[7]\)</span>, while <span class="arithmatex">\(dp[8]\)</span> splits into <span class="arithmatex">\(dp[7]\)</span> and <span class="arithmatex">\(dp[6]\)</span>. Both contain <span class="arithmatex">\(dp[7]\)</span>.</p>
|
||||
<p>These subproblems in turn contain smaller overlapping subproblems, and the pattern repeats at deeper levels of the recursion tree. Most of the computation is wasted on solving the same subproblems repeatedly.</p>
|
||||
<h2 id="1412-method-2-memoized-search">14.1.2 Method 2: Memoized search<a class="headerlink" href="#1412-method-2-memoized-search" title="Permanent link">¶</a></h2>
|
||||
@@ -2921,8 +2921,8 @@ dp[i] = dp[i-1] + dp[i-2]
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20dfs%28i%3A%20int,%20mem%3A%20list%5Bint%5D%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22Memoized%20search%22%22%22%0A%20%20%20%20%23%20The%20values%20of%20dp%5B1%5D%20and%20dp%5B2%5D%20are%20known%3B%20return%20the%20corresponding%20value%0A%20%20%20%20if%20i%20%3D%3D%201%20or%20i%20%3D%3D%202%3A%0A%20%20%20%20%20%20%20%20return%20i%0A%20%20%20%20%23%20If%20dp%5Bi%5D%20has%20been%20recorded,%20return%20it%20directly%0A%20%20%20%20if%20mem%5Bi%5D%20%21%3D%20-1%3A%0A%20%20%20%20%20%20%20%20return%20mem%5Bi%5D%0A%20%20%20%20%23%20dp%5Bi%5D%20%3D%20dp%5Bi-1%5D%20%2B%20dp%5Bi-2%5D%0A%20%20%20%20count%20%3D%20dfs%28i%20-%201,%20mem%29%20%2B%20dfs%28i%20-%202,%20mem%29%0A%20%20%20%20%23%20Record%20dp%5Bi%5D%0A%20%20%20%20mem%5Bi%5D%20%3D%20count%0A%20%20%20%20return%20count%0A%0A%0Adef%20climbing_stairs_dfs_mem%28n%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22Climbing%20stairs%3A%20memoized%20search%22%22%22%0A%20%20%20%20%23%20mem%5Bi%5D%20stores%20the%20number%20of%20ways%20to%20reach%20step%20i%3B%20-1%20means%20no%20result%20has%20been%20recorded%0A%20%20%20%20mem%20%3D%20%5B-1%5D%20%2A%20%28n%20%2B%201%29%0A%20%20%20%20return%20dfs%28n,%20mem%29%0A%0A%0A%22%22%22Driver%20code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20n%20%3D%209%0A%0A%20%20%20%20res%20%3D%20climbing_stairs_dfs_mem%28n%29%0A%20%20%20%20print%28f%22Number%20of%20ways%20to%20climb%20%7Bn%7D%20stairs%3A%20%7Bres%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=5&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" rel="noopener noreferrer" target="_blank">View full screen ></a></div></p>
|
||||
</details>
|
||||
<p>As shown in Figure 14-4, <strong>memoization makes every overlapping subproblem require only one computation, reducing the time complexity to <span class="arithmatex">\(O(n)\)</span></strong>: a major improvement.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.png" data-dark-src="/assets/figure-svg/figures/81a693c2f81780f53930803f.json" data-src="/assets/figure-svg/figures/33806f0c0d0e2db5f5638556.json" style=";--figure-ratio:960.0/540.0"><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.svg" data-theme="light" tabindex="-1" type="image/svg+xml">Recursion tree for memoized search</object><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">Recursion tree for memoized search</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-4 Recursion tree for memoized search </p>
|
||||
<p><ha-svg-figure aria-label="Memoized search reuses previously computed states" class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.png" data-dark-src="/assets/figure-svg/figures/81a693c2f81780f53930803f.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/33806f0c0d0e2db5f5638556.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">Recursion tree for memoized search</object><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dfs_memo_tree.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">Recursion tree for memoized search</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-4 Recursion tree for memoized search </p><div class="ha-sr-only figure-description"><h3>Description of Figure 14-4: Memoized search reuses previously computed states</h3><p>On the first visit, memoized search computes and caches each non-base state along the left branch. When a right branch reaches the same state, its cached value still contributes to the parent’s sum.</p><p>Again counting ways to climb stairs by taking 1 or 2 steps at a time, with base cases dp[1] = 1 and dp[2] = 2, memoized search introduces an array mem to record computed non-base state values: base cases return immediately, while non-base states check mem first and expand further only if not yet recorded.</p><p>In the figure, the main first-time computation chain runs dp[9] → dp[8] → dp[7] → ... → dp[3], with dp[6] through dp[4] condensed as ellipses; dp[3] then splits into the base cases dp[2] and dp[1]. On the right, scissors icons explicitly mark cached reuse at dp[7], dp[6], and dp[5], while remaining reuse points are summarized by ellipses. Filling in the omitted segment from the code also reuses dp[4] inside dp[6] and dp[3] inside dp[5]; the right subproblem dp[2] of dp[4] returns directly as a base case rather than a cache hit.</p><p>For example, computing dp[9] first completes its left subproblem dp[8], during which dp[7] is already computed and stored; when evaluating the right subproblem (dp[7] marked with scissors), the search reads the cached value directly without expanding it again, and that value still contributes to the sum for dp[9].</p><p>The two tables below list the three reuse relationships explicitly shown in the figure and how the code handles base cases, first-time computations, and cache hits.</p><table><caption>Cached state reuses explicitly shown in the figure</caption><thead><tr><th scope="col">Parent state</th><th scope="col">Left subproblem completed first</th><th scope="col">Right subproblem read from cache</th></tr></thead><tbody><tr><th scope="row">dp[9]</th><td>dp[8]</td><td>dp[7]</td></tr><tr><th scope="row">dp[8]</th><td>dp[7]</td><td>dp[6]</td></tr><tr><th scope="row">dp[7]</th><td>dp[6] (shown as an ellipsis in the figure)</td><td>dp[5]</td></tr></tbody></table><table><caption>Handling of the three kinds of states</caption><thead><tr><th scope="col">Encountered state</th><th scope="col">Action</th></tr></thead><tbody><tr><th scope="row">dp[1], dp[2]</th><td>Return 1 or 2 directly</td></tr><tr><th scope="row">Non-base state, not yet recorded</th><td>Compute recursively, sum, store in mem, and return</td></tr><tr><th scope="row">Non-base state, already recorded</th><td>Return the value from mem directly; still added into parent sum</td></tr></tbody></table><p>Each non-base state is expanded and computed only once, and repeated lookups return the cached value directly, reducing the time complexity to O(n).</p></div>
|
||||
<h2 id="1413-method-3-dynamic-programming">14.1.3 Method 3: Dynamic programming<a class="headerlink" href="#1413-method-3-dynamic-programming" title="Permanent link">¶</a></h2>
|
||||
<p><strong>Memoized search is a top-down approach</strong>: start with the original problem (the root), recursively divide larger subproblems into smaller ones until reaching the smallest subproblems with known solutions (the leaves), then collect their solutions as recursion returns to construct the solution to the original problem.</p>
|
||||
<p>In contrast, <strong>dynamic programming is a bottom-up approach</strong>: start with the smallest subproblem solutions and iteratively build solutions to larger subproblems until the original problem is solved.</p>
|
||||
@@ -3168,8 +3168,8 @@ dp[i] = dp[i-1] + dp[i-2]
|
||||
<div style="margin-top: 5px;"><a href="https://pythontutor.com/iframe-embed.html#code=def%20climbing_stairs_dp%28n%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22Climbing%20stairs%3A%20dynamic%20programming%22%22%22%0A%20%20%20%20if%20n%20%3D%3D%201%20or%20n%20%3D%3D%202%3A%0A%20%20%20%20%20%20%20%20return%20n%0A%20%20%20%20%23%20Initialize%20the%20dp%20table%20to%20store%20subproblem%20solutions%0A%20%20%20%20dp%20%3D%20%5B0%5D%20%2A%20%28n%20%2B%201%29%0A%20%20%20%20%23%20Initial%20states%3A%20set%20the%20solutions%20to%20the%20smallest%20subproblems%0A%20%20%20%20dp%5B1%5D,%20dp%5B2%5D%20%3D%201,%202%0A%20%20%20%20%23%20State%20transitions%3A%20solve%20progressively%20larger%20subproblems%20using%20smaller%20ones%0A%20%20%20%20for%20i%20in%20range%283,%20n%20%2B%201%29%3A%0A%20%20%20%20%20%20%20%20dp%5Bi%5D%20%3D%20dp%5Bi%20-%201%5D%20%2B%20dp%5Bi%20-%202%5D%0A%20%20%20%20return%20dp%5Bn%5D%0A%0A%0A%22%22%22Driver%20code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20n%20%3D%209%0A%0A%20%20%20%20res%20%3D%20climbing_stairs_dp%28n%29%0A%20%20%20%20print%28f%22Number%20of%20ways%20to%20climb%20%7Bn%7D%20stairs%3A%20%7Bres%7D%22%29&codeDivHeight=800&codeDivWidth=600&cumulative=false&curInstr=4&heapPrimitives=nevernest&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false" rel="noopener noreferrer" target="_blank">View full screen ></a></div></p>
|
||||
</details>
|
||||
<p>Figure 14-5 traces the code's execution.</p>
|
||||
<p><ha-svg-figure class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.png" data-dark-src="/assets/figure-svg/figures/89137b1726045f60e0f93b89.json" data-src="/assets/figure-svg/figures/cc29e45fec0f9c177ae1b1c3.json" style=";--figure-ratio:960.0/540.0"><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.svg" data-theme="light" tabindex="-1" type="image/svg+xml">Dynamic programming for climbing stairs</object><object data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.dark.svg" data-theme="dark" tabindex="-1" type="image/svg+xml">Dynamic programming for climbing stairs</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-5 Dynamic programming for climbing stairs </p>
|
||||
<p><ha-svg-figure aria-label="Iteratively computing ways to climb stairs from initial states" class="animation-figure" data-book-key="en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.png" data-dark-src="/assets/figure-svg/figures/89137b1726045f60e0f93b89.json" data-figure-accessible="" data-src="/assets/figure-svg/figures/cc29e45fec0f9c177ae1b1c3.json" role="img" style=";--figure-ratio:960.0/540.0"><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.svg" data-theme="light" inert="" tabindex="-1" type="image/svg+xml">Dynamic programming for climbing stairs</object><object aria-hidden="true" data="/en/chapter_dynamic_programming/intro_to_dynamic_programming.assets/climbing_stairs_dp.dark.svg" data-theme="dark" inert="" tabindex="-1" type="image/svg+xml">Dynamic programming for climbing stairs</object></ha-svg-figure></p>
|
||||
<p align="center"> Figure 14-5 Dynamic programming for climbing stairs </p><div class="ha-sr-only figure-description"><h3>Description of Figure 14-5: Iteratively computing ways to climb stairs from initial states</h3><p>Starting from the initial states dp[1] = 1 and dp[2] = 2, repeatedly sum the two preceding entries from left to right up to dp[9].</p><p>Each move climbs 1 or 2 steps, and dp[i] denotes the number of ways to reach step i. This figure shows bottom-up dynamic programming filling the table iteratively without a recursion call stack.</p><p>First set dp[1] = 1 and dp[2] = 2, then compute dp[i] = dp[i - 1] + dp[i - 2] in order from dp[3] through dp[9]: each entry depends only on the preceding two entries, both of which have already been computed when needed.</p><p>Nine cells are arranged horizontally in the figure, labeled only with the state names dp[1] through dp[9], while the initial values dp[1] = 1, dp[2] = 2 and the state transition equation are written below. The values 3, 5, 8, 13, 21, 34, and finally 55 at dp[9] are derived from those initial values and the equation rather than printed inside the cells. The table below lists each state's initial value or dependency together with its derived value.</p><table><caption>Dependencies and values derived from the recurrence</caption><thead><tr><th scope="col">State</th><th scope="col">Source</th><th scope="col">Value and basis</th></tr></thead><tbody><tr><th scope="row">dp[1]</th><td>Initial state</td><td>1 (initial value given in figure)</td></tr><tr><th scope="row">dp[2]</th><td>Initial state</td><td>2 (initial value given in figure)</td></tr><tr><th scope="row">dp[3]</th><td>dp[2] + dp[1]</td><td>3 (derived from equation)</td></tr><tr><th scope="row">dp[4]</th><td>dp[3] + dp[2]</td><td>5 (derived from equation)</td></tr><tr><th scope="row">dp[5]</th><td>dp[4] + dp[3]</td><td>8 (derived from equation)</td></tr><tr><th scope="row">dp[6]</th><td>dp[5] + dp[4]</td><td>13 (derived from equation)</td></tr><tr><th scope="row">dp[7]</th><td>dp[6] + dp[5]</td><td>21 (derived from equation)</td></tr><tr><th scope="row">dp[8]</th><td>dp[7] + dp[6]</td><td>34 (derived from equation)</td></tr><tr><th scope="row">dp[9]</th><td>dp[8] + dp[7]</td><td>55 (derived from equation)</td></tr></tbody></table><p>Bottom-up iteration computes each state only once and stops upon reaching the target state; from the initial values and transition equation in the figure, the target state dp[9] evaluates to 55 ways.</p></div>
|
||||
<p>Like backtracking, dynamic programming uses states to represent stages of solving a problem. Each state corresponds to a subproblem and its locally optimal solution. For climbing stairs, the state is the current step number <span class="arithmatex">\(i\)</span>.</p>
|
||||
<p>We can now summarize some common dynamic programming terminology.</p>
|
||||
<ul>
|
||||
@@ -3499,5 +3499,5 @@ dp[i] = dp[i-1] + dp[i-2]
|
||||
<script src="../../javascripts/mathjax.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js"></script>
|
||||
<script src="../../javascripts/animation_player.js"></script>
|
||||
<script defer="" src="/assets/figure-svg/js/bcdea376f01bc2bc0cac7c6c.js"></script><script defer="" src="/assets/figure-svg/js/e84f59519170c0f5ef238548.js"></script><script defer="" src="/assets/figure-svg/js/a704d8e80a80ddc71f2a03a7.js"></script><script defer="" src="/assets/figure-svg/js/bff17b8259339758cb1c4a06.js"></script></body>
|
||||
<script defer="" src="/assets/figure-svg/js/00174ff861e190f5c1f09e34.js"></script><script defer="" src="/assets/figure-svg/js/e84f59519170c0f5ef238548.js"></script><script defer="" src="/assets/figure-svg/js/a704d8e80a80ddc71f2a03a7.js"></script><script defer="" src="/assets/figure-svg/js/70ae82c6406c9bdbda8e8362.js"></script></body>
|
||||
</html>
|
||||
Binary file not shown.
Reference in New Issue
Block a user