Dynamic programming
導入済み
5:37
アルゴリズム設計と解析
This course teaches you to price an algorithm's design before you trust it with real data. The first two units cover analysis tools and divide and conquer. The…
英語のナレーション・英語と中国語の字幕を切り替え可能
このレッスンの内容
| English | 意味 |
|---|---|
| Dynamic programming/daɪˈnæmɪk ˈprəʊɡræmɪŋ/ | solving a problem by storing the answers to overlapping smaller problems and reusing them |
| dependency order/dɪˈpendənsi ˈɔːdə/ | 依存順 |
| DP table/ˌdiː ˈpiː ˈteɪbl/ | the table that stores the answer to each smaller problem in dynamic programming |
| memoisation/ˌmeməʊaɪˈzeɪʃn/ | Saving the results of function calls so repeated calls with the same inputs can reuse an earlier result. |
| descending order | |
| subsequence/ˈsʌbsekwəns/ | items taken from a sequence in order, not necessarily next to each other |
| Edit distance/ˈedɪt ˈdɪstəns/ | the fewest insertions, deletions and substitutions needed to turn one string into another |
| Matrix-chain/ˈmeɪtrɪks tʃeɪn/ | the problem of choosing the order of matrix multiplications that needs the fewest scalar multiplications |
Remember, do not recompute
- Dynamic programming 动态规划 solves each overlapping subproblem once, stores the answer, and builds bigger answers from the stored ones.
- A design has three parts: the recurrence, the base cases, and the dependency order 依赖顺序 in which to fill the DP table 动态规划表.
The DP design is —
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Three parts: what a cell means, where it starts, which direction to fill.
Put the steps of designing a dynamic programming solution in order.
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
The definition comes first because the recurrence and the fill order both depend on it; a cell is read only after every cell it uses has been written.
The exponential that was not
- Naive Fibonacci computes the same values again and again: $F(30)$ makes 2,692,537 calls, because the number of calls follows the same exponential recurrence. With memoisation 记忆化 (storing answers) there are only 29 subproblems: $\Theta(n)$.
- Coin change with coins 1, 3, 4: let $dp[i]$ be the fewest coins that make amount $i$. The last coin is some $c$, so $dp[i] = 1 + \min_c dp[i - c]$, with $dp[0] = 0$. Fill from small amounts up:
| $i$ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| $dp[i]$ | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
- For $i = 6$ the last coin is 1, 3 or 4, leaving 5, 3 or 2. Those cost 2, 1 and 2 coins; the best is 1, so $dp[6] = 1 + 1 = 2$: the coins 3 + 3. Greedy takes the biggest coin first, 4 + 1 + 1, and pays 3 coins.
The same subproblem, again and again
Step through naive fib(5). fib(3) is computed twice and fib(2) three times; a memo table would compute each once, which is the whole idea of dynamic programming.
Naive fib(30) makes — calls
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
The call count is itself Fibonacci-exponential; memoised it is 29 subproblems.
Knapsack, small and exact
- Capacity 7; items (weight, value): (1,1), (3,4), (4,5), (5,7). Each item is taken or left. Let $dp[w]$ be the best value within capacity $w$ using the items seen so far.
- Adding an item of weight $w_i$ and value $v_i$: update $dp[w] \leftarrow \max(dp[w],\ dp[w - w_i] + v_i)$ for capacities $w$ in descending order 降序 from 7 to $w_i$, so each item is used at most once.
| after item | $w$ = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| (1,1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| (3,4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| (4,5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| (5,7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
- The answer is 9: items (3,4) and (4,5), weight 7. The tempting (5,7) plus (1,1) gives only 8. Every cell records a choice with a reason, so the table is the explanation.
Capacity 7 with items (1,1)(3,4)(4,5)(5,7): dp[7] = —
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Items 2 and 3: weight 7, value 9.
Longest common subsequence
-
A subsequence 子序列 keeps the order but may skip letters. For $X =$ ABCBDAB and $Y =$ BDCABA, fill a table $L[i][j]$, the LCS length of the first $i$ letters of $X$ and the first $j$ of $Y$.
-
If the letters match, $L[i][j] = L[i-1][j-1] + 1$ (one more than the cell up and to the left). Otherwise take the larger of the cell above and the cell to the left.
-
The corner gives $4$. To recover a longest subsequence, walk back from the corner: on a match go diagonally and keep the letter, otherwise step to the larger neighbour. Here that spells BCBA.
-
Besides the row and column of zeros, the table has $7 \times 6 = 42$ cells to fill, so the cost is $\Theta(mn)$.
-
Edit distance 编辑距离 fills the same shape with the costs of insert, delete and replace: kitten to sitting is $3$. Spell checkers and DNA tools compare strings this way.

What is the length of the longest common subsequence of ABCD and ACBD?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
ABD (or ACD) appears in both, in order; no common subsequence has 4 letters.
What is the edit distance from sunday to saturday (insert, delete or replace, each cost 1)?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Insert a and t after s, then replace n with r: 3 operations.
Longest increasing subsequence
- For $[3, 10, 2, 1, 20, 4, 6, 7]$, let $L[i]$ be the length of the longest increasing subsequence 子序列 that ends at position $i$: $L[i] = 1 + \max L[j]$ over earlier, smaller values, or $1$ if there are none. That is $\Theta(n^2)$, and it gives $\mathbf{4}$ (for example 3, 4, 6, 7).
- Keep only the smallest possible last value for each length, and find where each new value goes by binary search. That cuts the cost to $\Theta(n\log n)$.
Length of the longest increasing subsequence of $[3, 10, 2, 1, 20, 4, 6, 7]$?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
For example 3, 4, 6, 7 (or 2, 4, 6, 7).
Worked example: the order of matrix products
- $A$ is $10 \times 30$, $B$ is $30 \times 5$ and $C$ is $5 \times 60$. $(AB)C$ costs $10 \cdot 30 \cdot 5 + 10 \cdot 5 \cdot 60 = \mathbf{4500}$ multiplications; $A(BC)$ costs $30 \cdot 5 \cdot 60 + 10 \cdot 30 \cdot 60 = 27\,000$.
- The result is the same; only the cost differs. Matrix-chain 矩阵链 DP tries every last split $k$: $m[i][j] = \min_k(m[i][k] + m[k+1][j] + p_{i-1}p_kp_j)$, filled by increasing chain length, in $\Theta(n^3)$.
$A$ $10 \times 30$, $B$ $30 \times 5$, $C$ $5 \times 60$: fewest scalar multiplications for $ABC$?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
$(AB)C$: $1500 + 3000 = 4500$, against 27,000 for $A(BC)$.
Changing where the brackets go in $ABC$ changes the product matrix.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Matrix multiplication is associative; only the number of multiplications changes.
Marks that slip away
- Reading a cell before it is written. Fill the table in dependency order: for coin change, smaller amounts first.
- Memoising without overlap. Dynamic programming 动态规划 helps only when subproblems repeat; merge sort's halves never do.
- Losing the choice. Keep or trace back each cell's decision, or you get the value $9$ but not the items, 2 and 3.
Recap
- DP: a recurrence, base cases and a dependency order 依赖顺序 to fill the table.
- Memoised Fibonacci: $29$ subproblems instead of $2\,692\,537$ calls.
- Coins 1, 3, 4: $dp[6] = 2$; knapsack with capacity 7: $dp[7] = 9$.
何が問題でしたか?この内容はサイトの運営チームだけが確認します。