mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-24 12:42:23 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -1,79 +1,79 @@
|
||||
# Characteristics of Dynamic Programming Problems
|
||||
# Properties of dynamic programming problems
|
||||
|
||||
In the previous section, we learned how dynamic programming solves the original problem by decomposing it into subproblems. In fact, subproblem decomposition is a general algorithmic approach, with different emphases in divide and conquer, dynamic programming, and backtracking.
|
||||
The previous section showed how dynamic programming solves a problem by decomposing it into subproblems. Decomposition is a general algorithmic idea, but divide and conquer, dynamic programming, and backtracking use it differently.
|
||||
|
||||
- Divide and conquer algorithms recursively divide the original problem into multiple independent subproblems until the smallest subproblems are reached, and merge the solutions to the subproblems during backtracking to ultimately obtain the solution to the original problem.
|
||||
- Dynamic programming also recursively decomposes problems, but the main difference from divide and conquer algorithms is that subproblems in dynamic programming are interdependent, and many overlapping subproblems appear during the decomposition process.
|
||||
- Backtracking algorithms enumerate all possible solutions through trial and error, and avoid unnecessary search branches through pruning. The solution to the original problem consists of a series of decision steps, and we can regard the subsequence before each decision step as a subproblem.
|
||||
- Divide and conquer recursively splits a problem into independent subproblems until the smallest ones are reached, then combines their solutions as the recursion returns to solve the original problem.
|
||||
- Dynamic programming also decomposes problems recursively. Its main difference from divide and conquer is that its subproblems depend on one another, and many overlapping subproblems appear during decomposition.
|
||||
- Backtracking enumerates possible solutions by trying choices and undoing them, using pruning to avoid unnecessary branches. A solution consists of a sequence of decisions, and the prefix before each decision can be viewed as a subproblem.
|
||||
|
||||
In fact, dynamic programming is commonly used to solve optimization problems, which not only contain overlapping subproblems but also have two other major characteristics: optimal substructure and no aftereffects.
|
||||
Dynamic programming is often used for optimization problems. Besides overlapping subproblems, these problems have two key properties: optimal substructure and the no-aftereffect property.
|
||||
|
||||
## Optimal Substructure
|
||||
## Optimal substructure
|
||||
|
||||
We make a slight modification to the stair climbing problem to make it more suitable for demonstrating the concept of optimal substructure.
|
||||
Let's modify the climbing stairs problem slightly to illustrate optimal substructure more clearly.
|
||||
|
||||
!!! question "Climbing stairs with minimum cost"
|
||||
!!! question "Minimum cost to climb stairs"
|
||||
|
||||
Given a staircase, you can climb $1$ or $2$ steps at a time, and each step is labeled with a non-negative integer representing the cost of stepping on it. Given a non-negative integer array $cost$, where $cost[i]$ represents the cost of the $i$-th step and $cost[0]$ is the ground (starting point), what is the minimum cost required to reach the top?
|
||||
Given a staircase, you can climb $1$ or $2$ steps at a time. Each step has a nonnegative integer indicating the cost paid on that step. A nonnegative integer array $cost$ gives the costs: $cost[i]$ is the cost of step $i$, and $cost[0]$ refers to the ground (the starting point). What is the minimum cost of reaching the top?
|
||||
|
||||
As shown in the figure below, if the costs of the $1$st, $2$nd, and $3$rd steps are $1$, $10$, and $1$ respectively, then climbing from the ground to the $3$rd step requires a minimum cost of $2$.
|
||||
As shown in the figure below, if steps $1$, $2$, and $3$ cost $1$, $10$, and $1$, respectively, the minimum cost of reaching step $3$ from the ground is $2$.
|
||||
|
||||

|
||||

|
||||
|
||||
Let $dp[i]$ be the accumulated cost of climbing to the $i$-th step. Since the $i$-th step can only come from the $i-1$-th or $i-2$-th step, $dp[i]$ can only equal $dp[i-1] + cost[i]$ or $dp[i-2] + cost[i]$. To minimize the cost, we should choose the smaller of the two:
|
||||
Let $dp[i]$ be the total cost of reaching step $i$. Since step $i$ can only be reached from step $i - 1$ or $i - 2$, $dp[i]$ must be either $dp[i - 1] + cost[i]$ or $dp[i - 2] + cost[i]$. To minimize the cost, choose the smaller of the two:
|
||||
|
||||
$$
|
||||
dp[i] = \min(dp[i-1], dp[i-2]) + cost[i]
|
||||
$$
|
||||
|
||||
This leads us to the meaning of optimal substructure: **the optimal solution to the original problem is constructed from the optimal solutions to the subproblems**.
|
||||
This introduces the meaning of optimal substructure: **an optimal solution to the original problem is constructed from optimal solutions to its subproblems**.
|
||||
|
||||
This problem clearly has optimal substructure: we select the better one from the optimal solutions to the two subproblems $dp[i-1]$ and $dp[i-2]$, and use it to construct the optimal solution to the original problem $dp[i]$.
|
||||
This problem clearly has optimal substructure: choose the better of $dp[i-1]$ and $dp[i-2]$ and use it to construct the optimal solution $dp[i]$.
|
||||
|
||||
So, does the stair climbing problem from the previous section have optimal substructure? Its goal is to find the number of ways, which seems to be a counting problem, but if we change the question: "Find the maximum number of ways". We surprisingly discover that **although the problem before and after modification are equivalent, the optimal substructure has emerged**: the maximum number of ways for the $n$-th step equals the sum of the maximum number of ways for the $n-1$-th and $n-2$-th steps. Therefore, the interpretation of optimal substructure is quite flexible and will have different meanings in different problems.
|
||||
Does the climbing stairs problem from the previous section also have optimal substructure? Its goal is to count solutions, so it seems to be a counting problem. But rephrase the goal as finding the maximum number of solutions, and **although the problem remains equivalent, optimal substructure becomes apparent**: the maximum number of ways to reach step $n$ is the sum of the maximum numbers for steps $n-1$ and $n-2$. The interpretation of optimal substructure is therefore flexible and can vary by problem.
|
||||
|
||||
According to the state transition equation and the initial states $dp[1] = cost[1]$ and $dp[2] = cost[2]$, we can obtain the dynamic programming code:
|
||||
The state transition equation, together with the initial states $dp[1] = cost[1]$ and $dp[2] = cost[2]$, gives the following dynamic programming code:
|
||||
|
||||
```src
|
||||
[file]{min_cost_climbing_stairs_dp}-[class]{}-[func]{min_cost_climbing_stairs_dp}
|
||||
```
|
||||
|
||||
The figure below shows the dynamic programming process for the above code.
|
||||
The figure below illustrates this dynamic programming process.
|
||||
|
||||

|
||||

|
||||
|
||||
This problem can also be space-optimized, compressing from one dimension to zero, reducing the space complexity from $O(n)$ to $O(1)$:
|
||||
We can also reduce the state storage from a one-dimensional array to scalar variables, lowering the space complexity from $O(n)$ to $O(1)$:
|
||||
|
||||
```src
|
||||
[file]{min_cost_climbing_stairs_dp}-[class]{}-[func]{min_cost_climbing_stairs_dp_comp}
|
||||
```
|
||||
|
||||
## No Aftereffects
|
||||
## No-aftereffect property
|
||||
|
||||
No aftereffects is one of the important characteristics that enable dynamic programming to solve problems effectively. Its definition is: **given a certain state, its future development is only related to the current state and has nothing to do with all past states**.
|
||||
The no-aftereffect property is central to effective dynamic programming: **given a fully specified state, its future depends only on that state, not on the sequence of states that led to it**.
|
||||
|
||||
Taking the stair climbing problem as an example, given state $i$, it will develop into states $i+1$ and $i+2$, corresponding to jumping $1$ step and jumping $2$ steps, respectively. When making these two choices, we do not need to consider the states before state $i$, as they have no effect on the future of state $i$.
|
||||
In the climbing stairs problem, state $i$ can lead to $i+1$ or $i+2$, corresponding to moves of $1$ or $2$ steps. Neither choice requires us to consider states before $i$: they do not affect the future of state $i$.
|
||||
|
||||
However, if we add a constraint to the stair climbing problem, the situation changes.
|
||||
Adding a constraint changes the situation.
|
||||
|
||||
!!! question "Climbing stairs with constraint"
|
||||
!!! question "Climbing stairs with a constraint"
|
||||
|
||||
Given a staircase with $n$ steps, where you can climb $1$ or $2$ steps at a time, **but you cannot jump $1$ step in two consecutive rounds**. How many ways are there to climb to the top?
|
||||
Given a staircase with $n$ steps, you may climb $1$ or $2$ steps at a time, **but may not make two consecutive moves of $1$ step**. How many ways are there to reach the top?
|
||||
|
||||
As shown in the figure below, there are only $2$ feasible ways to climb to the $3$rd step. The path with three consecutive $1$-step jumps does not satisfy the constraint and is therefore discarded.
|
||||
As shown in the figure below, only $2$ ways remain to reach step $3$: taking $1$ step three times in a row violates the constraint and is discarded.
|
||||
|
||||

|
||||

|
||||
|
||||
In this problem, if the previous round was a jump of $1$ step, then the next round must jump $2$ steps. This means that **the next choice cannot be determined solely by the current state (current stair step number), but also depends on the previous state (the stair step number from the previous round)**.
|
||||
If the previous move climbed $1$ step, the next must climb $2$ steps. Thus, **the next choice cannot be determined by the current state (the current step number) alone; it also depends on the preceding state (the previous step number)**.
|
||||
|
||||
It is not difficult to see that this problem no longer satisfies no aftereffects, and the state transition equation $dp[i] = dp[i-1] + dp[i-2]$ also fails, because $dp[i-1]$ represents jumping $1$ step in this round, but it includes many solutions where "the previous round was a jump of $1$ step", which cannot be directly counted in $dp[i]$ to satisfy the constraint.
|
||||
The no-aftereffect property no longer holds with this state definition, and $dp[i] = dp[i-1] + dp[i-2]$ is no longer valid. Using $dp[i-1]$ means taking $1$ step now, but it includes many ways in which the preceding move also took $1$ step. We cannot simply add all of $dp[i-1]$ to $dp[i]$ without violating the constraint.
|
||||
|
||||
For this reason, we need to expand the state definition: **state $[i, j]$ represents being on the $i$-th step with the previous round having jumped $j$ steps**, where $j \in \{1, 2\}$. This state definition effectively distinguishes whether the previous round was a jump of $1$ step or $2$ steps, allowing us to determine where the current state came from.
|
||||
We therefore expand the state definition: **state $[i, j]$ means we are on step $i$ and the previous move climbed $j$ steps**, where $j \in \{1, 2\}$. This distinguishes whether the preceding move climbed $1$ or $2$ steps, allowing us to determine how the current state could have been reached.
|
||||
|
||||
- When the previous round jumped $1$ step, the round before that could only choose to jump $2$ steps, i.e., $dp[i, 1]$ can only transition from $dp[i-1, 2]$.
|
||||
- When the previous round jumped $2$ steps, the round before that could choose to jump $1$ step or $2$ steps, i.e., $dp[i, 2]$ can transition from $dp[i-2, 1]$ or $dp[i-2, 2]$.
|
||||
- If the previous move climbed $1$ step, the move before it must have climbed $2$ steps. Thus, $dp[i, 1]$ can only come from $dp[i-1, 2]$.
|
||||
- If the previous move climbed $2$ steps, the move before it could have climbed $1$ or $2$ steps. Thus, $dp[i, 2]$ can come from $dp[i-2, 1]$ or $dp[i-2, 2]$.
|
||||
|
||||
As shown in the figure below, under this definition, $dp[i, j]$ represents the number of ways for state $[i, j]$. The state transition equation is then:
|
||||
As shown in the figure below, $dp[i, j]$ now counts the ways to reach state $[i, j]$. The state transition equations are:
|
||||
|
||||
$$
|
||||
\begin{cases}
|
||||
@@ -82,20 +82,20 @@ dp[i, 2] = dp[i-2, 1] + dp[i-2, 2]
|
||||
\end{cases}
|
||||
$$
|
||||
|
||||

|
||||

|
||||
|
||||
Finally, return $dp[n, 1] + dp[n, 2]$, where the sum of the two represents the total number of ways to climb to the $n$-th step:
|
||||
Finally, return $dp[n, 1] + dp[n, 2]$, the total number of ways to reach step $n$:
|
||||
|
||||
```src
|
||||
[file]{climbing_stairs_constraint_dp}-[class]{}-[func]{climbing_stairs_constraint_dp}
|
||||
```
|
||||
|
||||
In the above case, since we only need to consider one more preceding state, we can still make the problem satisfy no aftereffects by expanding the state definition. However, some problems have very severe "aftereffects".
|
||||
In this example, only one preceding state mattered, so expanding the state definition restored the no-aftereffect property. Some problems, however, depend much more strongly on their history.
|
||||
|
||||
!!! question "Climbing stairs with obstacle generation"
|
||||
!!! question "Climbing stairs that generate obstacles"
|
||||
|
||||
Given a staircase with $n$ steps, where you can climb $1$ or $2$ steps at a time. **Whenever you reach the $i$-th step, the system automatically places an obstacle on the $2i$-th step, and no subsequent round is allowed to jump to the $2i$-th step**. For example, if the first two rounds jump to the $2$nd and $3$rd steps, then afterwards you cannot jump to the $4$th and $6$th steps. How many ways are there to climb to the top?
|
||||
Given a staircase with $n$ steps, you may climb $1$ or $2$ steps at a time. **Whenever you reach step $i$, the system places an obstacle on step $2i$, and you may never land on step $2i$ afterward**. For example, if your first two moves land on steps $2$ and $3$, then steps $4$ and $6$ are blocked for all later moves. How many ways are there to reach the top?
|
||||
|
||||
In this problem, the next jump depends on all past states, because each jump places obstacles on higher steps, affecting future jumps. For such problems, dynamic programming is often difficult to solve.
|
||||
Here, each next move depends on all previous states, because every move places an obstacle higher up and affects future moves. Such problems are often difficult to solve with dynamic programming.
|
||||
|
||||
In fact, many complex combinatorial optimization problems (such as the traveling salesman problem) do not satisfy no aftereffects. For such problems, we usually use other methods, such as heuristic search, genetic algorithms, and reinforcement learning, to obtain usable locally optimal solutions within a limited time.
|
||||
Many complex combinatorial optimization problems, such as the traveling salesperson problem, do not satisfy the no-aftereffect property. For such problems, we often choose other methods, such as heuristic search, genetic algorithms, or reinforcement learning, to obtain useful locally optimal solutions within a limited time.
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
# Dynamic Programming Problem-Solving Approach
|
||||
# Solving dynamic programming problems
|
||||
|
||||
The previous two sections introduced the main characteristics of dynamic programming problems. Next, let us explore two more practical issues together.
|
||||
The previous two sections introduced the main properties of dynamic programming problems. We will now explore two practical questions.
|
||||
|
||||
1. How to determine whether a problem is a dynamic programming problem?
|
||||
2. What is the complete process for solving a dynamic programming problem, and where should we start?
|
||||
1. How can we recognize a dynamic programming problem?
|
||||
2. Where should we start, and what are the steps for solving one?
|
||||
|
||||
## Problem Identification
|
||||
## Recognizing the problem
|
||||
|
||||
Generally speaking, if a problem contains overlapping subproblems, optimal substructure, and satisfies no aftereffects, then it is usually suitable for solving with dynamic programming. However, it is difficult to directly extract these characteristics from the problem description. Therefore, we usually relax the conditions and **first observe whether the problem is suitable for solving with backtracking (exhaustive search)**.
|
||||
In general, a problem is suitable for dynamic programming if it has overlapping subproblems, optimal substructure, and the no-aftereffect property. These can be difficult to identify directly from a problem statement, so we usually start with a broader test: **could backtracking (exhaustive search) solve it**?
|
||||
|
||||
**Problems suitable for solving with backtracking usually satisfy the "decision tree model"**, which means the problem can be described using a tree structure, where each node represents a decision and each path represents a sequence of decisions.
|
||||
**Problems suited to backtracking usually fit a decision tree model**. They can be represented as a tree in which each node is a decision and each path is a sequence of decisions.
|
||||
|
||||
In other words, if a problem contains an explicit concept of decisions, and the solution is generated through a series of decisions, then it satisfies the decision tree model and can usually be solved using backtracking.
|
||||
In other words, if a problem has clear choices and a solution is produced through a sequence of them, it fits the decision tree model and can usually be solved by backtracking.
|
||||
|
||||
On this basis, dynamic programming problems also have some positive indicators.
|
||||
Beyond this, some signs make dynamic programming more promising.
|
||||
|
||||
- The problem contains descriptions such as maximum (minimum) or most (least), indicating optimization.
|
||||
- The problem's state can be represented using a list, multi-dimensional matrix, or tree, and a state has a recurrence relation with its surrounding states.
|
||||
- The problem asks for an optimum, such as a maximum, minimum, greatest number, or smallest number.
|
||||
- States can be represented by a list, a multidimensional matrix, or a tree, and a recurrence relates each state to nearby states.
|
||||
|
||||
Correspondingly, there are also some negative indicators.
|
||||
Other signs make it less promising.
|
||||
|
||||
- The goal of the problem is to find all possible solutions, rather than finding the optimal solution.
|
||||
- The problem description has obvious permutation and combination characteristics, requiring the return of specific multiple solutions.
|
||||
- The goal is to find all possible solutions rather than an optimal one.
|
||||
- The problem explicitly involves permutations or combinations and asks for multiple concrete arrangements.
|
||||
|
||||
If a problem satisfies the decision tree model and has relatively obvious positive indicators, we can assume it is a dynamic programming problem and verify that assumption during the solving process.
|
||||
If a problem fits the decision tree model and has clear positive signs, we can tentatively treat it as a dynamic programming problem and verify that assumption while solving it.
|
||||
|
||||
## Problem-Solving Steps
|
||||
## Steps for solving the problem
|
||||
|
||||
The problem-solving process for dynamic programming varies depending on the nature and difficulty of the problem, but generally follows these steps: describe decisions, define states, establish the $dp$ table, derive state transition equations, determine boundary conditions, etc.
|
||||
The process varies with the problem's nature and difficulty, but usually includes describing the decisions, defining states, creating a $dp$ table, deriving a state transition equation, and identifying boundary conditions.
|
||||
|
||||
To illustrate the problem-solving steps more vividly, we use a classic problem "minimum path sum" as an example.
|
||||
To make these steps concrete, we will use the classic minimum path sum problem.
|
||||
|
||||
!!! question
|
||||
|
||||
Given an $n \times m$ two-dimensional grid `grid` in which each cell contains a non-negative integer representing its cost, a robot starts from the top-left cell and can only move down or right at each step until reaching the bottom-right cell. Return the minimum path sum from the top-left to the bottom-right.
|
||||
Given an $n \times m$ grid `grid`, each cell contains a nonnegative integer representing its cost. A robot starts at the top-left cell and can move one cell down or right at a time until it reaches the bottom-right cell. Return the minimum path sum from the top-left to the bottom-right.
|
||||
|
||||
The figure below shows an example where the minimum path sum for the given grid is $13$.
|
||||
In the example shown in the figure below, the minimum path sum is $13$.
|
||||
|
||||

|
||||

|
||||
|
||||
**Step 1: Think about the decisions in each round, define the state, and thus obtain the $dp$ table**
|
||||
**Step 1: Identify each decision, define the state, and establish the $dp$ table**
|
||||
|
||||
The decision in each round of this problem is to move one step down or right from the current cell. Let the row and column indices of the current cell be $[i, j]$. After moving down or right, the indices become $[i+1, j]$ or $[i, j+1]$. Therefore, the state should include two variables, the row index and column index, denoted as $[i, j]$.
|
||||
Each decision moves one cell down or right. If the current cell has indices $[i, j]$, the next indices are $[i+1, j]$ or $[i, j+1]$. The state therefore contains two variables, the row and column indices, and is denoted by $[i, j]$.
|
||||
|
||||
State $[i, j]$ corresponds to the subproblem: **the minimum path sum from the starting point $[0, 0]$ to $[i, j]$**, denoted as $dp[i, j]$.
|
||||
State $[i, j]$ corresponds to the subproblem of finding the minimum path sum from the starting point $[0, 0]$ to $[i, j]$. Its solution is $dp[i, j]$.
|
||||
|
||||
From this, we obtain the two-dimensional $dp$ matrix shown in the figure below, whose size is the same as the input grid $grid$.
|
||||
This gives the two-dimensional $dp$ matrix shown in the figure below, with the same dimensions as the input $grid$.
|
||||
|
||||

|
||||
|
||||
!!! note
|
||||
|
||||
The dynamic programming and backtracking processes can be described as a sequence of decisions, and the state consists of all decision variables. It should contain all variables describing the progress of problem-solving, and should contain sufficient information to derive the next state.
|
||||
Dynamic programming and backtracking can be described as sequences of decisions. A state consists of the decision variables and should contain every variable needed to describe progress, with enough information to derive the next state.
|
||||
|
||||
Each state corresponds to a subproblem. A $dp$ table stores the solutions to all subproblems, with one dimension of the $dp$ table for each independent state variable. In essence, the $dp$ table maps states to subproblem solutions.
|
||||
|
||||
Each state corresponds to a subproblem, and we define a $dp$ table to store the solutions to all subproblems. Each independent variable of the state is a dimension of the $dp$ table. Essentially, the $dp$ table is a mapping between states and solutions to subproblems.
|
||||
**Step 2: Identify optimal substructure and derive the state transition equation**
|
||||
|
||||
**Step 2: Identify the optimal substructure, and then derive the state transition equation**
|
||||
State $[i, j]$ can only be reached from the cell above, $[i-1, j]$, or the cell to the left, $[i, j-1]$. The optimal substructure is therefore that the minimum path sum to $[i, j]$ is determined by the smaller of the minimum path sums to $[i, j-1]$ and $[i-1, j]$.
|
||||
|
||||
For state $[i, j]$, it can only transition from the cell above $[i-1, j]$ or the cell to the left $[i, j-1]$. Therefore, the optimal substructure is: the minimum path sum to reach $[i, j]$ is determined by the smaller of the minimum path sums of $[i, j-1]$ and $[i-1, j]$.
|
||||
|
||||
Based on the above analysis, the state transition equation shown in the figure below can be derived:
|
||||
This gives the state transition equation illustrated in the figure below:
|
||||
|
||||
$$
|
||||
dp[i, j] = \min(dp[i-1, j], dp[i, j-1]) + grid[i, j]
|
||||
@@ -69,75 +69,75 @@ $$
|
||||
|
||||
!!! note
|
||||
|
||||
Based on the defined $dp$ table, think about the relationship between the original problem and subproblems, and find the method to construct the optimal solution to the original problem from the optimal solutions to the subproblems, which is the optimal substructure.
|
||||
Using the defined $dp$ table, examine the relationship between the original problem and its subproblems. Find how to construct an optimal solution from optimal subproblem solutions: this is the optimal substructure.
|
||||
|
||||
Once we identify the optimal substructure, we can use it to construct the state transition equation.
|
||||
Once we identify optimal substructure, we can use it to build the state transition equation.
|
||||
|
||||
**Step 3: Determine boundary conditions and state transition order**
|
||||
**Step 3: Determine the boundary conditions and evaluation order**
|
||||
|
||||
In this problem, states in the first row can only come from the state to their left, and states in the first column can only come from the state above them. Therefore, the first row $i = 0$ and first column $j = 0$ are boundary conditions.
|
||||
A state in the first row can only come from its left, and a state in the first column can only come from above. Thus, the first row $i = 0$ and first column $j = 0$ define the boundary conditions.
|
||||
|
||||
As shown in the figure below, since each cell transitions from the cell to its left and the cell above it, we use loops to traverse the matrix, with the outer loop traversing rows and the inner loop traversing columns.
|
||||
As shown in the figure below, each cell depends on the cells to its left and above. We therefore traverse the matrix with an outer loop over rows and an inner loop over columns.
|
||||
|
||||

|
||||

|
||||
|
||||
!!! note
|
||||
|
||||
Boundary conditions in dynamic programming are used to initialize the $dp$ table, while in search they are used for pruning.
|
||||
Boundary conditions initialize the $dp$ table in dynamic programming and support pruning in search.
|
||||
|
||||
The key to choosing an evaluation order is ensuring that all smaller subproblems needed by the current state have already been solved correctly.
|
||||
|
||||
The core of state transition order is to ensure that when computing the solution to the current problem, all the smaller subproblems it depends on have already been computed correctly.
|
||||
We could now write the dynamic programming solution directly. However, decomposing a problem is a top-down way of thinking, so implementing "brute-force search $\rightarrow$ memoized search $\rightarrow$ dynamic programming" often follows our reasoning more naturally.
|
||||
|
||||
Based on the above analysis, we can directly write the dynamic programming code. However, subproblem decomposition is a top-down approach, so implementing in the order "brute force search $\rightarrow$ memoization $\rightarrow$ dynamic programming" is more aligned with thinking habits.
|
||||
### Method 1: Brute-force search
|
||||
|
||||
### Method 1: Brute Force Search
|
||||
Starting from $[i, j]$, recursively decompose the problem into smaller states $[i-1, j]$ and $[i, j-1]$. The recursive function has the following elements.
|
||||
|
||||
Starting from state $[i, j]$, we continuously decompose it into smaller states $[i-1, j]$ and $[i, j-1]$. The recursive function includes the following elements.
|
||||
- **Parameters**: The state $[i, j]$.
|
||||
- **Return value**: The minimum path sum $dp[i, j]$ from $[0, 0]$ to $[i, j]$.
|
||||
- **Base case**: When $i = 0$ and $j = 0$, return $grid[0, 0]$.
|
||||
- **Pruning**: If $i < 0$ or $j < 0$, the indices are out of bounds. Return cost $+\infty$ to mark the path as infeasible.
|
||||
|
||||
- **Recursive parameters**: state $[i, j]$.
|
||||
- **Return value**: minimum path sum from $[0, 0]$ to $[i, j]$, which is $dp[i, j]$.
|
||||
- **Termination condition**: when $i = 0$ and $j = 0$, return cost $grid[0, 0]$.
|
||||
- **Pruning**: when $i < 0$ or $j < 0$, the index is out of bounds, return cost $+\infty$, representing infeasibility.
|
||||
|
||||
The implementation code is as follows:
|
||||
The implementation is as follows:
|
||||
|
||||
```src
|
||||
[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dfs}
|
||||
```
|
||||
|
||||
The figure below shows the recursion tree rooted at $dp[2, 1]$, which includes some overlapping subproblems whose number will increase sharply as the size of grid `grid` grows.
|
||||
The figure below shows the recursion tree rooted at $dp[2, 1]$. It includes overlapping subproblems, whose number grows rapidly with the size of `grid`.
|
||||
|
||||
Essentially, the reason for overlapping subproblems is: **there are multiple paths from the top-left corner to reach a certain cell**.
|
||||
The underlying reason for overlapping subproblems is that **multiple paths can reach the same cell from the top-left corner**.
|
||||
|
||||

|
||||

|
||||
|
||||
Each state has two choices, down and right, so the total number of steps from the top-left corner to the bottom-right corner is $m + n - 2$, giving a worst-case time complexity of $O(2^{m + n})$, where $n$ and $m$ are the number of rows and columns of the grid, respectively. Note that this calculation does not account for situations near the grid boundaries, where only one choice remains when reaching the grid boundary, so the actual number of paths will be somewhat less.
|
||||
Each state offers two choices, down and right, and reaching the bottom-right corner takes $m + n - 2$ moves. The worst-case time complexity is therefore $O(2^{m + n})$, where $n$ and $m$ are the numbers of rows and columns. This estimate ignores the grid boundaries, where only one choice remains, so the actual number of paths is smaller.
|
||||
|
||||
### Method 2: Memoization
|
||||
### Method 2: Memoized search
|
||||
|
||||
We introduce a memo list `mem` of the same size as grid `grid` to record the solutions to subproblems and prune overlapping subproblems:
|
||||
Introduce a memoization table `mem` with the same dimensions as `grid` to store subproblem solutions and prune repeated subproblems:
|
||||
|
||||
```src
|
||||
[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dfs_mem}
|
||||
```
|
||||
|
||||
As shown in the figure below, after introducing memoization, all subproblem solutions only need to be computed once, so the time complexity depends on the total number of states, which is the grid size $O(nm)$.
|
||||
As shown in the figure below, memoization ensures that every subproblem is solved only once. The time complexity is therefore determined by the number of states, the grid size $O(nm)$.
|
||||
|
||||

|
||||

|
||||
|
||||
### Method 3: Dynamic Programming
|
||||
### Method 3: Dynamic programming
|
||||
|
||||
Implement the dynamic programming solution based on iteration, as shown in the code below:
|
||||
The following code implements dynamic programming iteratively:
|
||||
|
||||
```src
|
||||
[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dp}
|
||||
```
|
||||
|
||||
The figure below shows the state transition process for minimum path sum, which traverses the entire grid, **thus the time complexity is $O(nm)$**.
|
||||
The figure below shows the state transitions for minimum path sum. They visit the entire grid, **so the time complexity is $O(nm)$**.
|
||||
|
||||
The array `dp` has size $n \times m$, **thus the space complexity is $O(nm)$**.
|
||||
The array `dp` has dimensions $n \times m$, **so the space complexity is $O(nm)$**.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -172,11 +172,11 @@ The array `dp` has size $n \times m$, **thus the space complexity is $O(nm)$**.
|
||||
=== "<12>"
|
||||

|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
Since each cell is only related to the cell to its left and the cell above it, we can use a single-row array to implement the $dp$ table.
|
||||
Each cell depends only on the cells to its left and above, so a single-row array is enough to represent the $dp$ table.
|
||||
|
||||
Note that since the array `dp` can only represent the state of one row, we cannot initialize the first column state in advance, but rather update it when traversing each row:
|
||||
Because `dp` stores only one row of states, we cannot initialize the entire first column in advance. Instead, update its entry when processing each row:
|
||||
|
||||
```src
|
||||
[file]{min_path_sum}-[class]{}-[func]{min_path_sum_dp_comp}
|
||||
|
||||
@@ -1,80 +1,80 @@
|
||||
# Edit Distance Problem
|
||||
# Edit distance problem
|
||||
|
||||
Edit distance, also known as Levenshtein distance, refers to the minimum number of edits required to transform one string into another, commonly used in information retrieval and natural language processing to measure the similarity between two sequences.
|
||||
Edit distance, also called Levenshtein distance, is the minimum number of edits needed to transform one string into another. It is commonly used in information retrieval and natural language processing to measure similarity between sequences.
|
||||
|
||||
!!! question
|
||||
|
||||
Given two strings $s$ and $t$, return the minimum number of edits required to transform $s$ into $t$.
|
||||
Given two strings $s$ and $t$, return the minimum number of edits needed to transform $s$ into $t$.
|
||||
|
||||
Three edits are allowed: insert a character, delete a character, or replace a character with any other character.
|
||||
|
||||
You can perform three types of edit operations on a string: insert a character, delete a character, or replace a character with any other character.
|
||||
As shown in the figure below, transforming `kitten` into `sitting` takes 3 edits: 2 replacements and 1 insertion. Transforming `hello` into `algo` also takes 3 edits: 2 replacements and 1 deletion.
|
||||
|
||||
As shown in the figure below, transforming `kitten` into `sitting` requires 3 edits, including 2 replacements and 1 insertion; transforming `hello` into `algo` requires 3 steps, including 2 replacements and 1 deletion.
|
||||

|
||||
|
||||

|
||||
**Edit distance fits naturally into a decision tree model**. Strings are nodes, and each decision (an edit) is an edge.
|
||||
|
||||
**The edit distance problem can be naturally explained using the decision tree model**. Strings correspond to tree nodes, and each edit operation corresponds to an edge in the tree.
|
||||
As shown in the figure below, without restrictions on the edits, each node can have many outgoing edges, one for each possible operation. Thus, many paths can transform `hello` into `algo`.
|
||||
|
||||
As shown in the figure below, without restricting operations, each node can branch into many edges, with each edge corresponding to one operation, meaning there are many possible paths to transform `hello` into `algo`.
|
||||
From the decision tree perspective, the goal is to find the shortest path between nodes `hello` and `algo`.
|
||||
|
||||
From the perspective of the decision tree, the goal of this problem is to find the shortest path between node `hello` and node `algo`.
|
||||

|
||||
|
||||

|
||||
### Dynamic programming approach
|
||||
|
||||
### Dynamic Programming Approach
|
||||
**Step 1: Identify each decision, define the state, and establish the $dp$ table**
|
||||
|
||||
**Step 1: Think about the decisions in each round, define the state, and thus obtain the $dp$ table**
|
||||
Each decision applies one edit to string $s$.
|
||||
|
||||
Each round of decision involves performing one edit operation on string $s$.
|
||||
We want each edit to reduce the problem's size so that we can form subproblems. Let the lengths of $s$ and $t$ be $n$ and $m$. First consider their last characters, $s[n-1]$ and $t[m-1]$.
|
||||
|
||||
We want the problem size to gradually decrease during the editing process so that we can construct subproblems. Let the lengths of strings $s$ and $t$ be $n$ and $m$ respectively. We first consider the tail characters of the two strings, $s[n-1]$ and $t[m-1]$.
|
||||
- If $s[n-1]$ and $t[m-1]$ match, skip them and consider $s[n-2]$ and $t[m-2]$.
|
||||
- If $s[n-1]$ and $t[m-1]$ differ, apply an edit to $s$ (insertion, deletion, or replacement) to match the endings, allowing us to move on to a smaller problem.
|
||||
|
||||
- If $s[n-1]$ and $t[m-1]$ are the same, we can skip them and directly consider $s[n-2]$ and $t[m-2]$.
|
||||
- If $s[n-1]$ and $t[m-1]$ are different, we need to perform one edit on $s$ (insert, delete, or replace) to make the tail characters of the two strings the same, allowing us to skip them and consider a smaller-scale problem.
|
||||
Each decision (edit) in $s$ changes the characters still to be matched in $s$ and $t$. The state therefore specifies the $i$-th and $j$-th characters currently under consideration in $s$ and $t$, denoted by $[i, j]$.
|
||||
|
||||
In other words, each round of decision (edit operation) we make on string $s$ will change the remaining characters to be matched in $s$ and $t$. Therefore, the state is the $i$-th and $j$-th characters currently being considered in $s$ and $t$, denoted as $[i, j]$.
|
||||
State $[i, j]$ represents the subproblem of finding **the minimum number of edits needed to transform the first $i$ characters of $s$ into the first $j$ characters of $t$**.
|
||||
|
||||
State $[i, j]$ corresponds to the subproblem: **the minimum number of edits required to change the first $i$ characters of $s$ into the first $j$ characters of $t$**.
|
||||
This gives a two-dimensional $dp$ table of size $(n+1) \times (m+1)$.
|
||||
|
||||
From this, we obtain a two-dimensional $dp$ table of size $(n+1) \times (m+1)$.
|
||||
**Step 2: Identify optimal substructure and derive the state transition equation**
|
||||
|
||||
**Step 2: Identify the optimal substructure, and then derive the state transition equation**
|
||||
For subproblem $dp[i, j]$, the final characters are $s[i-1]$ and $t[j-1]$. The three possible edits give the cases shown in the figure below.
|
||||
|
||||
Consider subproblem $dp[i, j]$, where the tail characters of the corresponding two strings are $s[i-1]$ and $t[j-1]$, which can be divided into the three cases shown in the figure below based on different edit operations.
|
||||
1. Insert $t[j-1]$ after $s[i-1]$, leaving subproblem $dp[i, j-1]$.
|
||||
2. Delete $s[i-1]$, leaving subproblem $dp[i-1, j]$.
|
||||
3. Replace $s[i-1]$ with $t[j-1]$, leaving subproblem $dp[i-1, j-1]$.
|
||||
|
||||
1. Insert $t[j-1]$ after $s[i-1]$, then the remaining subproblem is $dp[i, j-1]$.
|
||||
2. Delete $s[i-1]$, then the remaining subproblem is $dp[i-1, j]$.
|
||||
3. Replace $s[i-1]$ with $t[j-1]$, then the remaining subproblem is $dp[i-1, j-1]$.
|
||||

|
||||
|
||||

|
||||
|
||||
Based on the above analysis, we obtain the optimal substructure: the minimum number of edits for $dp[i, j]$ equals the minimum of $dp[i, j-1]$, $dp[i-1, j]$, and $dp[i-1, j-1]$, plus the current edit cost of $1$. The corresponding state transition equation is:
|
||||
The optimal substructure follows: the minimum edit count $dp[i, j]$ is the smallest of $dp[i, j-1]$, $dp[i-1, j]$, and $dp[i-1, j-1]$, plus $1$ for the current edit. The state transition equation is:
|
||||
|
||||
$$
|
||||
dp[i, j] = \min(dp[i, j-1], dp[i-1, j], dp[i-1, j-1]) + 1
|
||||
$$
|
||||
|
||||
Please note that **when $s[i-1]$ and $t[j-1]$ are the same, no edit is required for the current character**, in which case the state transition equation is:
|
||||
When **$s[i-1]$ and $t[j-1]$ match, no edit is needed for the current characters**, and the state transition equation becomes:
|
||||
|
||||
$$
|
||||
dp[i, j] = dp[i-1, j-1]
|
||||
$$
|
||||
|
||||
**Step 3: Determine boundary conditions and state transition order**
|
||||
**Step 3: Determine the boundary conditions and evaluation order**
|
||||
|
||||
When both strings are empty, the number of edit steps is $0$, i.e., $dp[0, 0] = 0$. When $s$ is empty but $t$ is not, the minimum number of edit steps equals the length of $t$, i.e., the first row $dp[0, j] = j$. When $s$ is not empty but $t$ is empty, the minimum number of edit steps equals the length of $s$, i.e., the first column $dp[i, 0] = i$.
|
||||
If both strings are empty, $0$ edits are needed, so $dp[0, 0] = 0$. If $s$ is empty but $t$ is not, the minimum edit count is the length of $t$, giving the first row $dp[0, j] = j$. If $s$ is nonempty but $t$ is empty, the count is the length of $s$, giving the first column $dp[i, 0] = i$.
|
||||
|
||||
Observing the state transition equation, the solution $dp[i, j]$ depends on solutions to the left, above, and upper-left, so the entire $dp$ table can be traversed in order through two nested loops.
|
||||
The solution $dp[i, j]$ depends on entries to its left, above, and upper left, so two nested loops can traverse the $dp$ table in increasing index order.
|
||||
|
||||
### Code Implementation
|
||||
### Code implementation
|
||||
|
||||
```src
|
||||
[file]{edit_distance}-[class]{}-[func]{edit_distance_dp}
|
||||
```
|
||||
|
||||
As shown in the figure below, the state transition process for the edit distance problem is very similar to that of the knapsack problem; both can be viewed as the process of filling a two-dimensional grid.
|
||||
As shown in the figure below, the state transition process resembles that of the knapsack problem: both fill a two-dimensional grid.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -118,11 +118,11 @@ As shown in the figure below, the state transition process for the edit distance
|
||||
=== "<15>"
|
||||

|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
Since $dp[i, j]$ depends on the states above $dp[i-1, j]$, to the left $dp[i, j-1]$, and at the upper-left $dp[i-1, j-1]$, forward traversal will lose the upper-left state $dp[i-1, j-1]$, while reverse traversal cannot construct $dp[i, j-1]$ in advance, so neither traversal order is suitable.
|
||||
The state $dp[i,j]$ depends on $dp[i-1, j]$ above, $dp[i, j-1]$ to the left, and $dp[i-1, j-1]$ at the upper left. Forward iteration loses $dp[i-1, j-1]$, while backward iteration cannot compute $dp[i, j-1]$ in advance. Neither order alone is sufficient.
|
||||
|
||||
For this reason, we can use a variable `leftup` to temporarily store the upper-left solution $dp[i-1, j-1]$, so we only need to consider the solutions to the left and above. This situation is the same as in the unbounded knapsack problem, so we can use forward traversal. The code is as follows:
|
||||
We can use a variable `leftup` to preserve the upper-left solution $dp[i-1, j-1]$, leaving only the left and upper entries to consider. The situation then matches unbounded knapsack, and forward iteration works. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{edit_distance}-[class]{}-[func]{edit_distance_dp_comp}
|
||||
|
||||
@@ -1,111 +1,111 @@
|
||||
# Exercises
|
||||
|
||||
## Concept Review
|
||||
## Check your understanding
|
||||
|
||||
### When Is Dynamic Programming Appropriate?
|
||||
### When is dynamic programming a good fit?
|
||||
|
||||
A student says, "Whenever a recurrence can be written, dynamic programming should be used."
|
||||
For each task below, decide whether dynamic programming, backtracking, or a loop or mathematical formula without a `dp` table is more appropriate. Give one key reason.
|
||||
A student says, “Whenever you can write a recurrence relation, you should use dynamic programming.”
|
||||
For each task below, decide whether dynamic programming, backtracking, or a loop or mathematical formula without a `dp` table is the best fit. Give one key reason for each choice.
|
||||
|
||||
<!-- numbered-subquestions -->
|
||||
|
||||
1. Using coin denominations `[1, 3, 4]`, make an amount of 6 with the fewest coins. Each denomination may be used repeatedly.
|
||||
1. Find the minimum number of coins needed to make an amount of 6 using denominations `[1, 3, 4]`. Each denomination can be used any number of times.
|
||||
2. Output all permutations of `[1, 2, 3]`.
|
||||
3. Calculate $1 + 2 + \dots + n$.
|
||||
|
||||
For the task you consider suitable for dynamic programming, also state what `dp[i]` represents.
|
||||
For the task you consider suitable for dynamic programming, also explain what `dp[i]` represents.
|
||||
|
||||
??? success "Answer"
|
||||
??? success "Reference answer"
|
||||
|
||||
1. Dynamic programming is suitable. Let `dp[i]` be the minimum number of coins needed to make amount `i`.
|
||||
For every coin `c` that does not exceed `i`, `dp[i-c] + 1` is a candidate answer,
|
||||
and the minimum of these candidates is chosen. Different choices repeatedly encounter the same amounts, and an optimal solution for a larger amount can be built from optimal solutions for smaller amounts.
|
||||
The answer for amount 6 is 2, using `3 + 3`.
|
||||
1. Dynamic programming is a good fit. Let `dp[i]` be the minimum number of coins needed to make an amount of `i`.
|
||||
For each coin `c` whose denomination does not exceed `i`, consider `dp[i-c] + 1` as a candidate answer,
|
||||
then take the minimum of these candidates. Different choices repeatedly lead to the same amounts, and an optimal solution for a larger amount can be built from optimal solutions for smaller amounts.
|
||||
The answer for an amount of 6 is 2: `3 + 3`.
|
||||
|
||||
2. Backtracking is suitable. The task requires generating all 6 permutations one by one. Backtracking can systematically make a choice, continue searching,
|
||||
undo the choice, and then try another branch. Regardless of the method, actually outputting every permutation requires enumerating them.
|
||||
2. Use backtracking. The task requires generating all 6 permutations individually. Backtracking systematically makes a choice, continues the search,
|
||||
then undoes the choice and explores other branches. Whatever method you use, outputting all the permutations requires enumerating them.
|
||||
|
||||
3. A loop or the arithmetic-series formula is sufficient. Although the recurrence `S(i) = S(i-1) + i` can be written, calculating `S(i)` depends on only one smaller value, `S(i-1)`.
|
||||
Each partial sum needs to be calculated only once, so there are no repeated subproblems and no need for a `dp` table. "A recurrence can be written" does not mean "dynamic programming is needed."
|
||||
3. A loop or the formula for an arithmetic series is sufficient. Although you can write `S(i) = S(i-1) + i`, calculating `S(i)` depends on just one smaller value, `S(i-1)`.
|
||||
Each partial sum needs to be calculated only once, so there are no overlapping subproblems and no need for a `dp` table. Being able to write a recurrence does not mean you need dynamic programming.
|
||||
|
||||
### Calculating One Cell in a Knapsack Table
|
||||
### How do you calculate a cell in the knapsack table?
|
||||
|
||||
Consider this 0-1 knapsack problem: item weights `wgt = [1, 2, 3]`, values `val = [5, 11, 15]`, and knapsack capacity 4.
|
||||
`dp[i][c]` is the maximum value obtainable using only the first $i$ items with a knapsack capacity limit of $c$;
|
||||
the knapsack does not have to be filled exactly.
|
||||
Consider a 0-1 knapsack problem with item weights `wgt = [1, 2, 3]`, values `val = [5, 11, 15]`, and a knapsack capacity of 4.
|
||||
Here, `dp[i][c]` is the maximum value obtainable using only the first $i$ items with a capacity limit of $c$.
|
||||
The knapsack does not have to be filled exactly.
|
||||
|
||||
Calculate only the state `dp[3][4]`. You are given `dp[2][4] = 16` and `dp[2][1] = 5`:
|
||||
Calculate just the state `dp[3][4]`. You are given `dp[2][4] = 16` and `dp[2][1] = 5`.
|
||||
|
||||
<!-- numbered-subquestions -->
|
||||
|
||||
1. If the third item is not selected, what is the candidate value?
|
||||
2. If the third item is selected, how much capacity remains, and what is the candidate value?
|
||||
3. What should `dp[3][4]` be? Which items does this value correspond to selecting?
|
||||
1. What is the candidate value if you do not take item 3?
|
||||
2. If you take item 3, how much capacity remains, and what is the candidate value?
|
||||
3. What should `dp[3][4]` be? Which items does this solution take?
|
||||
|
||||
??? success "Answer"
|
||||
??? success "Reference answer"
|
||||
|
||||
1. If the third item is not selected, keep the result from the first two items. The candidate value is `dp[2][4] = 16`.
|
||||
1. If you do not take item 3, use the result for the first two items. The candidate value is `dp[2][4] = 16`.
|
||||
|
||||
2. The third item has weight 3, so capacity $4-3=1$ remains after it is placed in the knapsack. The candidate value is
|
||||
2. Item 3 weighs 3, so taking it leaves a capacity of $4-3=1$. The candidate value is
|
||||
`dp[2][1] + 15 = 5 + 15 = 20`.
|
||||
|
||||
3. Comparing 16 and 20 gives `dp[3][4] = 20`. This corresponds to selecting the first and third items,
|
||||
whose total weight is $1+3=4$ and total value is $5+15=20$.
|
||||
3. Comparing 16 and 20 gives `dp[3][4] = 20`. This solution takes items 1 and 3,
|
||||
with a total weight of $1+3=4$ and a total value of $5+15=20$.
|
||||
|
||||
This state calculation demonstrates one "select or do not select" comparison in the 0-1 knapsack problem.
|
||||
Calculating this state illustrates a single “take it or leave it” comparison in the 0-1 knapsack problem.
|
||||
|
||||
### In Which Order Should Knapsack Capacities Be Updated?
|
||||
### In what order should knapsack capacities be updated?
|
||||
|
||||
A 0-1 knapsack problem has only one item, with weight 2 and value 5, and the knapsack has capacity 4.
|
||||
The item can be selected at most once. The initial one-dimensional array is `dp = [0, 0, 0, 0, 0]`.
|
||||
A 0-1 knapsack problem has just one item, with weight 2 and value 5. The knapsack capacity is 4.
|
||||
Each item can be taken at most once, and the initial one-dimensional array is `dp = [0, 0, 0, 0, 0]`.
|
||||
|
||||
A student processes the item by updating capacities from 2 to 4:
|
||||
A student processes this item by updating capacities from 2 to 4:
|
||||
|
||||
- After updating `dp[2]`, its value is 5.
|
||||
- After updating `dp[3]`, its value is also 5.
|
||||
- When updating `dp[4]`, the student uses the newly obtained `dp[2]`, producing `dp[4] = 10`.
|
||||
- Updating `dp[2]` gives 5.
|
||||
- Updating `dp[3]` also gives 5.
|
||||
- When updating `dp[4]`, the student uses the newly computed `dp[2]`, obtaining `dp[4] = 10`.
|
||||
|
||||
<!-- numbered-subquestions -->
|
||||
|
||||
1. Is `dp[4] = 10` correct? Why or why not?
|
||||
2. Given that each item may be selected at most once, what should `dp[4]` be?
|
||||
3. When processing each item, should capacities be updated from largest to smallest or from smallest to largest? What problem does this avoid?
|
||||
2. Given that each item can be taken at most once, what should `dp[4]` be?
|
||||
3. When processing each item, should capacities be updated from largest to smallest or from smallest to largest? What problem does this prevent?
|
||||
|
||||
??? success "Answer"
|
||||
??? success "Reference answer"
|
||||
|
||||
1. The result is incorrect. A value of 10 is equivalent to placing the item with value 5 into the knapsack twice,
|
||||
violating the condition that each item may be selected at most once.
|
||||
1. The result is incorrect. A value of 10 means taking the item worth 5 twice,
|
||||
which violates the condition that each item can be taken at most once.
|
||||
|
||||
2. The knapsack can contain at most this one item, so the correct value of `dp[4]` is 5.
|
||||
2. The knapsack can contain only this one item, so the correct value of `dp[4]` is 5.
|
||||
|
||||
3. Capacities should be updated from largest to smallest, in the order 4, 3, 2.
|
||||
Then, when calculating `dp[c]`, the value read from `dp[c-2]` still comes from before the current item was processed,
|
||||
preventing the current item from being reused during the same round.
|
||||
3. Update capacities from largest to smallest: 4, then 3, then 2.
|
||||
This ensures that when calculating `dp[c]`, the value read from `dp[c-2]` is still the result from before the current item was processed.
|
||||
The current item therefore cannot be used more than once in the same round of updates.
|
||||
|
||||
## Programming Exercises
|
||||
## Programming exercises
|
||||
|
||||
### Number of Ways to Climb Stairs
|
||||
### Counting ways to climb stairs
|
||||
|
||||
A staircase has `n` steps. Each move climbs either 1 or 2 steps, and you must land exactly on step `n`.
|
||||
Calculate the number of distinct ways to reach the top. Assume `n >= 1`; ways are distinguished only by their sequence of 1-step and 2-step moves.
|
||||
Use a one-dimensional dynamic programming array. For now, do not use the space optimization that keeps only two states.
|
||||
A staircase has `n` steps. You can climb either 1 or 2 steps at a time and must land exactly on step `n`.
|
||||
Calculate the number of different ways to climb the staircase. Assume `n >= 1`; two ways differ only in their sequence of 1-step and 2-step moves.
|
||||
Use a one-dimensional dynamic programming array. For now, do not use the space optimization that retains only two states.
|
||||
|
||||
??? tip "Hints"
|
||||
|
||||
1. The last move to step i can cover only 1 or 2 steps
|
||||
2. Therefore, dp[i] = dp[i-1] + dp[i-2]
|
||||
3. Handle the cases where n is 1 or 2 first, then fill the table starting from step 3
|
||||
1. The final move to step i must be either a 1-step or a 2-step move.
|
||||
2. This gives dp[i] = dp[i-1] + dp[i-2].
|
||||
3. Handle n = 1 and n = 2 first, then fill the table starting at step 3.
|
||||
|
||||
[LeetCode](https://leetcode.com/problems/climbing-stairs/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }
|
||||
|
||||
### 0-1 Knapsack
|
||||
### 0-1 knapsack
|
||||
|
||||
You are given equal-length arrays `wgt` and `val`. Item `i` has positive integer weight `wgt[i]` and non-negative integer value `val[i]`.
|
||||
The knapsack capacity `cap` is a non-negative integer. Each item may be selected at most once. Find the maximum total value that can be placed in the knapsack
|
||||
without exceeding `cap`. Use one-dimensional dynamic programming.
|
||||
You are given arrays `wgt` and `val` of equal length. Item `i` has a positive integer weight `wgt[i]` and a nonnegative integer value `val[i]`.
|
||||
The knapsack capacity `cap` is a nonnegative integer. Each item can be taken at most once. Find the maximum total value
|
||||
that fits in the knapsack without exceeding `cap` in total weight. Use one-dimensional dynamic programming.
|
||||
|
||||
??? tip "Hints"
|
||||
|
||||
1. Initialize an array dp of length cap + 1, where dp[c] is the maximum value for a capacity limit of c
|
||||
2. When processing item i, compare dp[c], which does not select it, with dp[c-wgt[i]] + val[i], which does
|
||||
3. Update capacities from largest to smallest to avoid selecting the current item repeatedly in the same round
|
||||
1. Initialize an array dp of length cap + 1, where dp[c] is the maximum value obtainable with a capacity limit of c.
|
||||
2. When processing item i, compare dp[c] for leaving it out with dp[c-wgt[i]] + val[i] for taking it.
|
||||
3. Update capacities from largest to smallest to avoid taking the current item more than once in the same round.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Dynamic Programming
|
||||
# Dynamic programming
|
||||
|
||||

|
||||
|
||||
!!! abstract
|
||||
|
||||
Streams flow into rivers, rivers flow into the sea.
|
||||
|
||||
Dynamic programming combines solutions to small problems into the answer to a large problem, leading us step by step to the other shore of problem-solving.
|
||||
Streams flow into rivers, and rivers flow into the sea.
|
||||
|
||||
Dynamic programming brings together solutions to small problems to answer a larger one, guiding us step by step to the other shore.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 62 KiB |
@@ -1,67 +1,67 @@
|
||||
# Introduction to Dynamic Programming
|
||||
# Introduction to dynamic programming
|
||||
|
||||
<u>Dynamic programming</u> is an important algorithmic paradigm that decomposes a problem into a series of smaller subproblems and avoids redundant computation by storing the solutions to subproblems, thereby significantly improving time efficiency.
|
||||
<u>Dynamic programming</u> is an important algorithmic paradigm. It breaks a problem into smaller subproblems and stores their solutions to avoid repeated computation, greatly improving time efficiency.
|
||||
|
||||
In this section, we start with a classic example, first presenting its brute force backtracking solution, observing the overlapping subproblems within it, and then gradually deriving a more efficient dynamic programming solution.
|
||||
We will start with a classic example, give a brute-force backtracking solution, identify its overlapping subproblems, and gradually derive a more efficient dynamic programming solution.
|
||||
|
||||
!!! question "Climbing stairs"
|
||||
|
||||
Given a staircase with $n$ steps, where you can climb $1$ or $2$ steps at a time, how many different ways are there to reach the top?
|
||||
Given a staircase with $n$ steps, you may climb $1$ or $2$ steps at a time. How many ways are there to reach the top?
|
||||
|
||||
As shown in the figure below, for a $3$-step staircase, there are $3$ different ways to reach the top.
|
||||
As shown in the figure below, a staircase with $3$ steps has $3$ possible ways to reach the top.
|
||||
|
||||

|
||||

|
||||
|
||||
The goal of this problem is to determine the number of ways, so **we can consider using backtracking to enumerate all possibilities**. Specifically, imagine climbing stairs as a multi-round selection process: starting from the ground, choosing to go up $1$ or $2$ steps in each round, incrementing the count by $1$ whenever the top of the stairs is reached, and pruning when exceeding the top. The code is as follows:
|
||||
The goal is to count solutions, so **we can use backtracking to enumerate every possibility**. View climbing as a sequence of choices: starting from the ground, choose to climb $1$ or $2$ steps each time. Add $1$ to the count whenever we reach the top, and prune any branch that goes beyond it. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{climbing_stairs_backtrack}-[class]{}-[func]{climbing_stairs_backtrack}
|
||||
```
|
||||
|
||||
## Method 1: Brute Force Search
|
||||
## Method 1: Brute-force search
|
||||
|
||||
Backtracking algorithms typically do not explicitly decompose problems, but rather treat solving the problem as a series of decision steps, searching for all possible solutions through trial and pruning.
|
||||
Backtracking usually does not explicitly decompose the problem. Instead, it treats a solution as a sequence of decisions and searches all possible solutions through trial and pruning.
|
||||
|
||||
We can try to analyze this problem from the perspective of problem decomposition. Let the number of ways to climb to the $i$-th step be $dp[i]$, then $dp[i]$ is the original problem, and its subproblems include:
|
||||
Let's analyze this problem through decomposition. Let $dp[i]$ be the number of ways to reach step $i$. The original problem is $dp[i]$, and its subproblems include:
|
||||
|
||||
$$
|
||||
dp[i-1], dp[i-2], \dots, dp[2], dp[1]
|
||||
$$
|
||||
|
||||
Since we can only go up $1$ or $2$ steps in each round, when we stand on the $i$-th step, we could only have been on the $i-1$-th or $i-2$-th step in the previous round. In other words, we can only reach the $i$-th step from the $i-1$-th or $i-2$-th step.
|
||||
Since each move climbs $1$ or $2$ steps, when we stand on step $i$, we must previously have been on step $i - 1$ or $i - 2$. In other words, step $i$ can only be reached from step $i -1$ or $i - 2$.
|
||||
|
||||
This leads to an important conclusion: **the number of ways to climb to the $i-1$-th step plus the number of ways to climb to the $i-2$-th step equals the number of ways to climb to the $i$-th step**. The formula is as follows:
|
||||
This gives an important result: **the number of ways to reach step $i - 1$ plus the number of ways to reach step $i - 2$ equals the number of ways to reach step $i$**. In symbols:
|
||||
|
||||
$$
|
||||
dp[i] = dp[i-1] + dp[i-2]
|
||||
$$
|
||||
|
||||
This means that in the stair climbing problem, there exists a recurrence relation among the subproblems, and **the solution to the original problem can be constructed from the solutions to the subproblems**. The figure below illustrates this recurrence relation.
|
||||
Thus, the subproblems are linked by a recurrence: **the solution to the original problem can be constructed from subproblem solutions**. The figure below illustrates this relationship.
|
||||
|
||||

|
||||

|
||||
|
||||
We can obtain a brute force search solution based on the recurrence formula. Starting from $dp[n]$, **recursively decompose a larger problem into the sum of two smaller problems**, until reaching the smallest subproblems $dp[1]$ and $dp[2]$ and returning. Among them, the solutions to the smallest subproblems are known, namely $dp[1] = 1$ and $dp[2] = 2$, representing $1$ and $2$ ways to climb to the $1$st and $2$nd steps, respectively.
|
||||
The recurrence gives a brute-force search solution. Starting at $dp[n]$, **recursively express a larger problem as the sum of two smaller ones** until reaching $dp[1]$ or $dp[2]$. Their solutions are known: $dp[1] = 1$ and $dp[2] = 2$, meaning steps $1$ and $2$ can be reached in $1$ and $2$ ways, respectively.
|
||||
|
||||
Observe the following code: like standard backtracking code, it also uses depth-first search but is more concise:
|
||||
Like the standard backtracking code, the following code performs depth-first search, but is more concise:
|
||||
|
||||
```src
|
||||
[file]{climbing_stairs_dfs}-[class]{}-[func]{climbing_stairs_dfs}
|
||||
```
|
||||
|
||||
The figure below shows the recursion tree formed by brute force search. For the problem $dp[n]$, the depth of its recursion tree is $n$, with a time complexity of $O(2^n)$. Exponential growth is explosive; if we input a relatively large $n$, the wait can be very long.
|
||||
The figure below shows the recursion tree for brute-force search. For $dp[n]$, its depth is $n$, and the time complexity is $O(2^n)$. Exponential growth is explosive, so a relatively large $n$ leads to a very long wait.
|
||||
|
||||

|
||||
|
||||
Observing the above figure, **the exponential time complexity is caused by "overlapping subproblems"**. For example, $dp[9]$ is decomposed into $dp[8]$ and $dp[7]$, and $dp[8]$ is decomposed into $dp[7]$ and $dp[6]$, both of which contain the subproblem $dp[7]$.
|
||||
As the figure above shows, **overlapping subproblems cause the exponential time complexity**. For example, $dp[9]$ splits into $dp[8]$ and $dp[7]$, while $dp[8]$ splits into $dp[7]$ and $dp[6]$. Both contain $dp[7]$.
|
||||
|
||||
And so on, subproblems contain smaller overlapping subproblems, ad infinitum. The vast majority of computational resources are wasted on these overlapping subproblems.
|
||||
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.
|
||||
|
||||
## Method 2: Memoization
|
||||
## Method 2: Memoized search
|
||||
|
||||
To improve algorithm efficiency, **we want all overlapping subproblems to be computed only once**. For this purpose, we declare an array `mem` to record the solution to each subproblem and prune overlapping subproblems during the search process.
|
||||
To improve efficiency, **we want every overlapping subproblem to be solved only once**. Introduce an array `mem` to record each solution and prune repeated subproblems during the search.
|
||||
|
||||
1. When computing $dp[i]$ for the first time, we record it in `mem[i]` for later use.
|
||||
2. When we need to compute $dp[i]$ again, we can directly retrieve the result from `mem[i]`, thereby avoiding redundant computation of that subproblem.
|
||||
1. The first time we calculate $dp[i]$, store it in `mem[i]` for later use.
|
||||
2. When $dp[i]$ is needed again, retrieve it directly from `mem[i]` instead of recomputing it.
|
||||
|
||||
The code is as follows:
|
||||
|
||||
@@ -69,42 +69,42 @@ The code is as follows:
|
||||
[file]{climbing_stairs_dfs_mem}-[class]{}-[func]{climbing_stairs_dfs_mem}
|
||||
```
|
||||
|
||||
Observe the figure below: **after memoization, all overlapping subproblems need to be computed only once, reducing the time complexity to $O(n)$**, which is a tremendous leap.
|
||||
As shown in the figure below, **memoization makes every overlapping subproblem require only one computation, reducing the time complexity to $O(n)$**: a major improvement.
|
||||
|
||||

|
||||

|
||||
|
||||
## Method 3: Dynamic Programming
|
||||
## Method 3: Dynamic programming
|
||||
|
||||
**Memoization is a "top-down" method**: we start from the original problem (root node), recursively decompose larger subproblems into smaller ones, until reaching the smallest known subproblems (leaf nodes). Afterward, by backtracking, we collect the solutions to the subproblems layer by layer to construct the solution to the original problem.
|
||||
**Memoized search is a top-down approach**: 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.
|
||||
|
||||
In contrast, **dynamic programming is a "bottom-up" method**: starting from the solutions to the smallest subproblems, iteratively constructing solutions to larger subproblems until obtaining the solution to the original problem.
|
||||
In contrast, **dynamic programming is a bottom-up approach**: start with the smallest subproblem solutions and iteratively build solutions to larger subproblems until the original problem is solved.
|
||||
|
||||
Since dynamic programming does not include a backtracking process, it only requires loop iteration for implementation and does not need recursion. In the following code, we initialize an array `dp` to store the solutions to subproblems, which serves the same recording function as the array `mem` in memoization:
|
||||
Because this dynamic programming process does not backtrack, it needs only iterative loops, not recursion. In the following code, the array `dp` stores subproblem solutions, serving the same role as `mem` in memoized search:
|
||||
|
||||
```src
|
||||
[file]{climbing_stairs_dp}-[class]{}-[func]{climbing_stairs_dp}
|
||||
```
|
||||
|
||||
The figure below simulates the execution process of the above code.
|
||||
The figure below traces the code's execution.
|
||||
|
||||

|
||||

|
||||
|
||||
Like backtracking algorithms, dynamic programming also uses the "state" concept to represent specific stages of problem solving, with each state corresponding to a subproblem and its corresponding local optimal solution. For example, the state in the stair climbing problem is defined as the current stair step number $i$.
|
||||
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 $i$.
|
||||
|
||||
Based on the above content, we can summarize the commonly used terminology in dynamic programming.
|
||||
We can now summarize some common dynamic programming terminology.
|
||||
|
||||
- The array `dp` is called the <u>dp table</u>, where $dp[i]$ represents the solution to the subproblem corresponding to state $i$.
|
||||
- The states corresponding to the smallest subproblems (the $1$st and $2$nd steps) are called <u>initial states</u>.
|
||||
- The recurrence formula $dp[i] = dp[i-1] + dp[i-2]$ is called the <u>state transition equation</u>.
|
||||
- The array `dp` is called the <u>dp table</u>, and $dp[i]$ stores the solution to the subproblem for state $i$.
|
||||
- The states for the smallest subproblems (steps $1$ and $2$) are called the <u>initial states</u>.
|
||||
- The recurrence $dp[i] = dp[i-1] + dp[i-2]$ is called the <u>state transition equation</u>.
|
||||
|
||||
## Space Optimization
|
||||
## Space optimization
|
||||
|
||||
Observant readers may have noticed that **since $dp[i]$ is only related to $dp[i-1]$ and $dp[i-2]$, we do not need to use an array `dp` to store the solutions to all subproblems**, and can instead use two variables that roll forward. The code is as follows:
|
||||
You may have noticed that **$dp[i]$ depends only on $dp[i-1]$ and $dp[i-2]$, so we do not need an entire `dp` array storing every subproblem solution**. Two variables updated as we proceed are enough. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{climbing_stairs_dp}-[class]{}-[func]{climbing_stairs_dp_comp}
|
||||
```
|
||||
|
||||
As the above code shows, by eliminating the space occupied by the array `dp`, the space complexity is reduced from $O(n)$ to $O(1)$.
|
||||
Removing the `dp` array reduces space complexity from $O(n)$ to $O(1)$.
|
||||
|
||||
In dynamic programming problems, the current state often depends only on a limited number of preceding states, allowing us to retain only the necessary states and save memory space through "dimension reduction". **This space optimization technique is called "rolling variable" or "rolling array"**.
|
||||
In dynamic programming, a state often depends on only a limited number of preceding states. We can keep just those needed, reducing the storage dimensions to save memory. **This technique is called using rolling variables or a rolling array**.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 47 KiB |
@@ -1,97 +1,97 @@
|
||||
# 0-1 Knapsack Problem
|
||||
# 0-1 knapsack problem
|
||||
|
||||
The knapsack problem is an excellent introductory problem for dynamic programming and is one of the most common problem forms in dynamic programming. It has many variants, such as the 0-1 knapsack problem, the unbounded knapsack problem, and the multiple knapsack problem.
|
||||
The knapsack problem is an excellent introduction to dynamic programming and one of its most common problem families. Variants include 0-1 knapsack, unbounded knapsack, and bounded knapsack.
|
||||
|
||||
In this section, we will first solve the most common 0-1 knapsack problem.
|
||||
We will begin with the most common variant, 0-1 knapsack.
|
||||
|
||||
!!! question
|
||||
|
||||
Given $n$ items and a knapsack with capacity $cap$, where the weight and value of the $i$-th item are $wgt[i-1]$ and $val[i-1]$, respectively. Each item can be selected at most once. What is the maximum value that can fit in the knapsack under the capacity limit?
|
||||
Given $n$ items, where item $i$ has weight $wgt[i-1]$ and value $val[i-1]$, and a knapsack of capacity $cap$, each item may be chosen only once. What is the maximum total value that fits within the capacity?
|
||||
|
||||
Observe the figure below. Since item number $i$ starts counting from $1$ and array indices start from $0$, item $i$ corresponds to weight $wgt[i-1]$ and value $val[i-1]$.
|
||||
As shown in the figure below, item numbers $i$ start at $1$, while array indices start at $0$. Item $i$ therefore has weight $wgt[i-1]$ and value $val[i-1]$.
|
||||
|
||||

|
||||

|
||||
|
||||
We can view the 0-1 knapsack problem as a process consisting of $n$ rounds of decisions, where for each item there are two decisions: not putting it in and putting it in, thus the problem satisfies the decision tree model.
|
||||
We can view 0-1 knapsack as $n$ rounds of decisions, with two choices for each item: leave it out or put it in. It therefore fits the decision tree model.
|
||||
|
||||
The goal of this problem is to find "the maximum value that can be placed in the knapsack within the capacity limit", so it is more likely to be a dynamic programming problem.
|
||||
The objective is to maximize value within a capacity limit, making dynamic programming a promising approach.
|
||||
|
||||
**Step 1: Think about the decisions in each round, define the state, and thus obtain the $dp$ table**
|
||||
**Step 1: Identify each decision, define the state, and establish the $dp$ table**
|
||||
|
||||
For each item, if not placed in the knapsack, the knapsack capacity remains unchanged; if placed in, the knapsack capacity decreases. From this, we can derive the state definition: current item number $i$ and knapsack capacity $c$, denoted as $[i, c]$.
|
||||
Leaving an item out keeps the available capacity unchanged; putting it in reduces the capacity. The state therefore consists of the current item number $i$ and capacity $c$, denoted by $[i, c]$.
|
||||
|
||||
State $[i, c]$ corresponds to the subproblem: **the maximum value among the first $i$ items in a knapsack of capacity $c$**, denoted as $dp[i, c]$.
|
||||
State $[i, c]$ represents the subproblem of finding **the maximum value obtainable from the first $i$ items with capacity $c$**, denoted by $dp[i, c]$.
|
||||
|
||||
What we need to find is $dp[n, cap]$, so we need a two-dimensional $dp$ table of size $(n+1) \times (cap+1)$.
|
||||
We seek $dp[n, cap]$, so we need a two-dimensional $dp$ table of size $(n+1) \times (cap+1)$.
|
||||
|
||||
**Step 2: Identify the optimal substructure, and then derive the state transition equation**
|
||||
**Step 2: Identify optimal substructure and derive the state transition equation**
|
||||
|
||||
After making the decision for item $i$, what remains is the subproblem of the first $i-1$ items, which can be divided into the following two cases.
|
||||
After deciding what to do with item $i$, the remaining subproblem concerns the first $i-1$ items. There are two cases.
|
||||
|
||||
- **Not putting item $i$**: The knapsack capacity remains unchanged, and the state changes to $[i-1, c]$.
|
||||
- **Putting item $i$**: The knapsack capacity decreases by $wgt[i-1]$, the value increases by $val[i-1]$, and the state changes to $[i-1, c-wgt[i-1]]$.
|
||||
- **Leave item $i$ out**: Capacity stays unchanged, and the remaining state is $[i-1, c]$.
|
||||
- **Put item $i$ in**: Capacity decreases by $wgt[i-1]$, value increases by $val[i-1]$, and the remaining state is $[i-1, c-wgt[i-1]]$.
|
||||
|
||||
The above analysis reveals the optimal substructure of this problem: **the maximum value $dp[i, c]$ equals the greater of the values obtained by not putting item $i$ into the knapsack and by putting it into the knapsack**. From this, the state transition equation can be derived:
|
||||
This reveals the optimal substructure: **the maximum value $dp[i, c]$ is the larger value obtained by leaving item $i$ out or putting item $i$ in**. The state transition equation is:
|
||||
|
||||
$$
|
||||
dp[i, c] = \max(dp[i-1, c], dp[i-1, c - wgt[i-1]] + val[i-1])
|
||||
$$
|
||||
|
||||
Note that if the weight of the current item $wgt[i - 1]$ exceeds the remaining knapsack capacity $c$, then the only option is not to put it in the knapsack.
|
||||
If the current item's weight $wgt[i - 1]$ exceeds the remaining capacity $c$, the only option is to leave it out.
|
||||
|
||||
**Step 3: Determine boundary conditions and state transition order**
|
||||
**Step 3: Determine the boundary conditions and evaluation order**
|
||||
|
||||
When there are no items or the knapsack capacity is $0$, the maximum value is $0$, i.e., the first column $dp[i, 0]$ and the first row $dp[0, c]$ are both equal to $0$.
|
||||
With no items or capacity $0$, the maximum value is $0$. Thus, the first column $dp[i, 0]$ and first row $dp[0, c]$ are both $0$.
|
||||
|
||||
The current state $[i, c]$ transitions from the state above $[i-1, c]$ and the upper-left state $[i-1, c-wgt[i-1]]$, so we can traverse the entire $dp$ table in forward order using two nested loops.
|
||||
The current state $[i, c]$ depends on $[i-1, c]$ above and $[i-1, c-wgt[i-1]]$ to the upper left, so two nested loops can traverse the $dp$ table in increasing index order.
|
||||
|
||||
Based on the above analysis, we will next implement the brute force search, memoization, and dynamic programming solutions in order.
|
||||
We will now implement brute-force search, memoized search, and dynamic programming in that order.
|
||||
|
||||
### Method 1: Brute Force Search
|
||||
### Method 1: Brute-force search
|
||||
|
||||
The search code includes the following elements.
|
||||
The search has the following elements.
|
||||
|
||||
- **Recursive parameters**: state $[i, c]$.
|
||||
- **Return value**: solution to the subproblem $dp[i, c]$.
|
||||
- **Termination condition**: when there are no items left ($i = 0$) or the remaining knapsack capacity is $0$, terminate the recursion and return value $0$.
|
||||
- **Pruning**: if the weight of the current item exceeds the remaining knapsack capacity, only the option of not putting it in is available.
|
||||
- **Parameters**: The state $[i, c]$.
|
||||
- **Return value**: The subproblem solution $dp[i, c]$.
|
||||
- **Base case**: If there are no items left, $i = 0$, or the remaining capacity is $0$, stop recursion and return value $0$.
|
||||
- **Pruning**: If the current item is heavier than the remaining capacity, only the choice to leave it out is allowed.
|
||||
|
||||
```src
|
||||
[file]{knapsack}-[class]{}-[func]{knapsack_dfs}
|
||||
```
|
||||
|
||||
As shown in the figure below, since each item generates two search branches, excluding it and including it, the time complexity is $O(2^n)$.
|
||||
As shown in the figure below, each item creates two branches, excluding it or including it, so the time complexity is $O(2^n)$.
|
||||
|
||||
Observing the recursion tree, it is easy to see overlapping subproblems, such as $dp[1, 10]$. When there are many items, large knapsack capacity, and especially many items with the same weight, the number of overlapping subproblems will increase significantly.
|
||||
The recursion tree contains overlapping subproblems, such as $dp[1, 10]$. Their number grows substantially with more items and larger capacity, especially when many items share the same weight.
|
||||
|
||||

|
||||

|
||||
|
||||
### Method 2: Memoization
|
||||
### Method 2: Memoized search
|
||||
|
||||
To ensure that overlapping subproblems are only computed once, we use a memo list `mem` to record the solutions to subproblems, where `mem[i][c]` corresponds to $dp[i, c]$.
|
||||
To solve each overlapping subproblem only once, use a memoization table `mem`, where `mem[i][c]` stores $dp[i, c]$.
|
||||
|
||||
After introducing memoization, **the time complexity depends on the number of subproblems**, which is $O(n \times cap)$. The implementation code is as follows:
|
||||
With memoization, **the time complexity depends on the number of subproblems**, giving $O(n \times cap)$. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{knapsack}-[class]{}-[func]{knapsack_dfs_mem}
|
||||
```
|
||||
|
||||
The figure below shows the search branches pruned in memoization.
|
||||
The figure below shows the branches pruned by memoized search.
|
||||
|
||||

|
||||

|
||||
|
||||
### Method 3: Dynamic Programming
|
||||
### Method 3: Dynamic programming
|
||||
|
||||
Dynamic programming is essentially the process of filling the $dp$ table during state transitions. The code is as follows:
|
||||
Dynamic programming essentially fills the $dp$ table using state transitions, as shown in the code below:
|
||||
|
||||
```src
|
||||
[file]{knapsack}-[class]{}-[func]{knapsack_dp}
|
||||
```
|
||||
|
||||
As shown in the figure below, both time complexity and space complexity are determined by the size of the array `dp`, which is $O(n \times cap)$.
|
||||
As shown in the figure below, both time and space complexity are determined by the size of `dp`: $O(n \times cap)$.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -132,19 +132,19 @@ As shown in the figure below, both time complexity and space complexity are dete
|
||||
=== "<14>"
|
||||

|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
Since each state is only related to the state in the row above it, we can use two arrays rolling forward to reduce the space complexity from $O(n \times cap)$ to $O(cap)$.
|
||||
Each state depends only on the previous row, so two rolling arrays reduce space complexity from $O(n \times cap)$ to $O(cap)$.
|
||||
|
||||
Further thinking, can we achieve space optimization using just one array? Observing, we can see that each state is transferred from the cell directly above or the cell in the upper-left. If there is only one array, when we start traversing row $i$, that array still stores the state of row $i-1$.
|
||||
Can we go further and use just one array? Each state depends on entries directly above or to the upper left. With one array, when we begin processing row $i$, it still holds the states from row $i-1$.
|
||||
|
||||
- If using forward traversal, then when traversing to $dp[i, j]$, the values in the upper-left $dp[i-1, 1]$ ~ $dp[i-1, j-1]$ may have already been overwritten, thus preventing correct state transition.
|
||||
- If using reverse traversal, there will be no overwriting issue, and state transition can proceed correctly.
|
||||
- With forward iteration, by the time we reach $dp[i, j]$, the upper-left values $dp[i-1, 1]$ ~ $dp[i-1, j-1]$ may have been overwritten, making the transition incorrect.
|
||||
- With backward iteration, these values are not overwritten before they are needed, so transitions remain correct.
|
||||
|
||||
The figure below shows the transition process from row $i = 1$ to row $i = 2$ using a single array. Please consider the difference between forward and reverse traversal.
|
||||
The figure below shows one array changing from row $i = 1$ to row $i = 2$. Consider how forward and backward iteration differ.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -161,7 +161,7 @@ The figure below shows the transition process from row $i = 1$ to row $i = 2$ us
|
||||
=== "<6>"
|
||||

|
||||
|
||||
In the code implementation, we simply need to delete the first dimension $i$ of the array `dp` and change the inner loop to reverse traversal:
|
||||
In the implementation, simply remove the first dimension $i$ from `dp` and reverse the inner loop:
|
||||
|
||||
```src
|
||||
[file]{knapsack}-[class]{}-[func]{knapsack_dp_comp}
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
# Summary
|
||||
|
||||
### Key Points
|
||||
### Key takeaways
|
||||
|
||||
- Dynamic programming decomposes problems and avoids redundant computation by storing the solutions to subproblems, thereby significantly improving computational efficiency.
|
||||
- Without considering time constraints, all dynamic programming problems can be solved using backtracking (brute force search), but the recursion tree contains a large number of overlapping subproblems, resulting in extremely low efficiency. By introducing a memo list, we can store the solutions to all computed subproblems, ensuring that overlapping subproblems are only computed once.
|
||||
- Memoization is a top-down recursive solution, while the corresponding dynamic programming is a bottom-up iterative solution, similar to "filling in a table". Since the current state only depends on certain local states, we can eliminate one dimension of the $dp$ table to reduce space complexity.
|
||||
- Subproblem decomposition is a general algorithmic approach, with different properties in divide and conquer, dynamic programming, and backtracking.
|
||||
- Dynamic programming problems have three major characteristics: overlapping subproblems, optimal substructure, and no aftereffects.
|
||||
- If the optimal solution to the original problem can be constructed from the optimal solutions to the subproblems, then it has optimal substructure.
|
||||
- No aftereffects means that for a given state, its future development is only related to that state and has nothing to do with all past states. Many combinatorial optimization problems do not satisfy this property and cannot be solved efficiently using dynamic programming.
|
||||
- Dynamic programming decomposes problems and stores subproblem solutions to avoid repeated computation and improve efficiency.
|
||||
- Without a time limit, every dynamic programming problem can be solved by backtracking (brute-force search). However, the recursion tree contains many overlapping subproblems, making it very inefficient. Memoization stores computed solutions so that each overlapping subproblem is solved only once.
|
||||
- Memoized search is a top-down recursive approach, while the corresponding dynamic programming solution works bottom up, like filling a table. Since the current state depends only on certain nearby states, removing a dimension from the $dp$ table can reduce space complexity.
|
||||
- Decomposing a problem into subproblems is a general algorithmic idea with different characteristics in divide and conquer, dynamic programming, and backtracking.
|
||||
- Dynamic programming problems have three key properties: overlapping subproblems, optimal substructure, and the no-aftereffect property.
|
||||
- A problem has optimal substructure if its optimal solution can be constructed from optimal solutions to subproblems.
|
||||
- The no-aftereffect property means a state's future depends only on that state, not on the history leading to it. Many combinatorial optimization problems lack this property and cannot be solved quickly with dynamic programming.
|
||||
|
||||
**Knapsack problem**
|
||||
**Knapsack problems**
|
||||
|
||||
- The knapsack problem is one of the most typical dynamic programming problems, with variants such as the 0-1 knapsack, unbounded knapsack, and multiple knapsack.
|
||||
- The state definition for the 0-1 knapsack is the maximum value achievable using the first $i$ items with a knapsack capacity of $c$. Based on the two decisions of not putting an item in the knapsack and putting it in, the optimal substructure can be identified and the state transition equation constructed. In space optimization, since each state depends on the state directly above and to the upper-left, the list needs to be traversed in reverse order to avoid overwriting the upper-left state.
|
||||
- The unbounded knapsack problem has no limit on the selection quantity of each type of item, so the state transition for choosing to put in an item differs from the 0-1 knapsack problem. Since the state depends on the state directly above and directly to the left, space optimization should use forward traversal.
|
||||
- The coin change problem is a variant of the unbounded knapsack problem. It changes from seeking the "maximum" value to seeking the "minimum" number of coins, so $\max()$ in the state transition equation should be changed to $\min()$. It changes from seeking "not exceeding" the knapsack capacity to seeking "exactly" making up the target amount, so $amt + 1$ is used to represent the invalid solution of "unable to make up the target amount".
|
||||
- Coin change problem II changes from seeking the "minimum number of coins" to seeking the "number of coin combinations", so the state transition equation correspondingly changes from $\min()$ to a summation operator.
|
||||
- Knapsack is one of the most typical dynamic programming problem families, with variants including 0-1, unbounded, and bounded knapsack.
|
||||
- In 0-1 knapsack, the state value is the maximum value obtainable from the first $i$ items within capacity $c$. The choices to exclude or include an item reveal optimal substructure and give the state transition equation. After space optimization, backward iteration is necessary because each state depends on entries above and to the upper left, which must not be overwritten prematurely.
|
||||
- Unbounded knapsack allows unlimited copies of each item, changing the transition for including an item. Because a state depends on entries directly above and to the left, space optimization requires forward iteration.
|
||||
- Coin change is a variant of unbounded knapsack. Minimizing the number of coins instead of maximizing value changes $\max()$ to $\min()$ in the transition. Requiring the target amount exactly, rather than staying within a capacity, calls for using $amt + 1$ to represent an infeasible solution.
|
||||
- Coin change II counts combinations instead of minimizing coin count, so the transition replaces $\min()$ with addition.
|
||||
|
||||
**Edit distance problem**
|
||||
**Edit distance**
|
||||
|
||||
- Edit distance (Levenshtein distance) is used to measure the similarity between two strings, defined as the minimum number of edit steps from one string to another, with edit operations including insert, delete, and replace.
|
||||
- The state definition for the edit distance problem is the minimum number of edit steps required to change the first $i$ characters of $s$ into the first $j$ characters of $t$. When $s[i-1] \ne t[j-1]$, there are three decisions: insert, delete, replace, each with corresponding remaining subproblems. From this, the optimal substructure can be identified and the state transition equation constructed. When $s[i-1] = t[j-1]$, no edit is required for the current character.
|
||||
- In edit distance, the state depends on the state directly above, directly to the left, and to the upper-left, so after space optimization, neither forward nor reverse traversal can correctly perform state transitions. For this reason, we use a variable to temporarily store the upper-left state, thus transforming to a situation equivalent to the unbounded knapsack problem, allowing for forward traversal after space optimization.
|
||||
- Edit distance (Levenshtein distance) measures similarity between strings. It is the minimum number of edits needed to turn one string into another, allowing insertion, deletion, and replacement.
|
||||
- The edit distance state is the minimum number of edits needed to transform the first $i$ characters of $s$ into the first $j$ characters of $t$. When $s[i-1] \ne t[j-1]$, insertion, deletion, and replacement each leave a corresponding subproblem, revealing optimal substructure and the state transition equation. When $s[i-1] = t[j-1]$, no edit is needed for those characters.
|
||||
- Edit distance depends on states above, to the left, and to the upper left, so neither forward nor backward iteration alone works after space optimization. A temporary variable preserves the upper-left state, reducing the situation to one like unbounded knapsack and allowing forward iteration.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 60 KiB |
@@ -1,49 +1,49 @@
|
||||
# Unbounded Knapsack Problem
|
||||
# Unbounded knapsack problem
|
||||
|
||||
In this section, we first solve another common knapsack problem: the unbounded knapsack, and then explore a special case of it: the coin change problem.
|
||||
We will now solve another common knapsack variant, unbounded knapsack, and then examine a special case: coin change.
|
||||
|
||||
## Unbounded Knapsack Problem
|
||||
## Unbounded knapsack
|
||||
|
||||
!!! question
|
||||
|
||||
Given $n$ items, where the weight of the $i$-th item is $wgt[i-1]$ and its value is $val[i-1]$, and a knapsack with capacity $cap$. **Each item can be selected multiple times**. What is the maximum value that can be placed in the knapsack within the capacity limit? An example is shown in the figure below.
|
||||
Given $n$ items, where item $i$ has weight $wgt[i-1]$ and value $val[i-1]$, and a knapsack of capacity $cap$, **each item may be chosen repeatedly**. What is the maximum value that fits within the capacity? An example is shown in the figure below.
|
||||
|
||||

|
||||

|
||||
|
||||
### Dynamic Programming Approach
|
||||
### Dynamic programming approach
|
||||
|
||||
The unbounded knapsack problem is very similar to the 0-1 knapsack problem, **differing only in that there is no limit on the number of times an item can be selected**.
|
||||
Unbounded knapsack is very similar to 0-1 knapsack. **The only difference is that there is no limit on how many times an item may be chosen**.
|
||||
|
||||
- In the 0-1 knapsack problem, there is only one of each type of item, so after placing item $i$ in the knapsack, we can only choose from the first $i-1$ items.
|
||||
- In the unbounded knapsack problem, the quantity of each type of item is unlimited, so after placing item $i$ in the knapsack, **we can still choose from the first $i$ items**.
|
||||
- In 0-1 knapsack, there is only one of each item, so after including item $i$, we can choose only from the first $i-1$ items.
|
||||
- In unbounded knapsack, each item has an unlimited supply, so after including item $i$, **we can still choose from the first $i$ items**.
|
||||
|
||||
Under the rules of the unbounded knapsack problem, the changes in state $[i, c]$ are divided into two cases.
|
||||
For unbounded knapsack, state $[i, c]$ has two cases.
|
||||
|
||||
- **Not putting item $i$**: Same as the 0-1 knapsack problem, transfer to $[i-1, c]$.
|
||||
- **Putting item $i$**: Different from the 0-1 knapsack problem, transfer to $[i, c-wgt[i-1]]$.
|
||||
- **Leave item $i$ out**: As in 0-1 knapsack, the remaining state is $[i-1, c]$.
|
||||
- **Put item $i$ in**: Unlike 0-1 knapsack, the remaining state is $[i, c-wgt[i-1]]$.
|
||||
|
||||
Thus, the state transition equation becomes:
|
||||
The state transition equation becomes:
|
||||
|
||||
$$
|
||||
dp[i, c] = \max(dp[i-1, c], dp[i, c - wgt[i-1]] + val[i-1])
|
||||
$$
|
||||
|
||||
### Code Implementation
|
||||
### Code implementation
|
||||
|
||||
Comparing the code for the two problems, there is one change in state transition from $i-1$ to $i$, with everything else identical:
|
||||
Compared with 0-1 knapsack, only one $i-1$ in the transition changes to $i$; the rest of the code is identical:
|
||||
|
||||
```src
|
||||
[file]{unbounded_knapsack}-[class]{}-[func]{unbounded_knapsack_dp}
|
||||
```
|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
Since the current state is transferred from states on the left and above, **after space optimization, each row in the $dp$ table should be traversed in forward order**.
|
||||
The current state depends on states to its left and above, **so after space optimization, each row of the $dp$ table must be processed in forward order**.
|
||||
|
||||
This traversal order is exactly opposite to the 0-1 knapsack. Please refer to the figure below to understand the difference between the two.
|
||||
This is the opposite of 0-1 knapsack. Use the figure below to understand the difference.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -60,67 +60,67 @@ This traversal order is exactly opposite to the 0-1 knapsack. Please refer to th
|
||||
=== "<6>"
|
||||

|
||||
|
||||
The code implementation is relatively simple, just delete the first dimension of the array `dp`:
|
||||
The implementation simply removes the first dimension of `dp`:
|
||||
|
||||
```src
|
||||
[file]{unbounded_knapsack}-[class]{}-[func]{unbounded_knapsack_dp_comp}
|
||||
```
|
||||
|
||||
## Coin Change Problem
|
||||
## Coin change problem
|
||||
|
||||
The knapsack problem represents a large class of dynamic programming problems and has many variants, such as the coin change problem.
|
||||
Knapsack represents a broad family of dynamic programming problems, with many variants such as coin change.
|
||||
|
||||
!!! question
|
||||
|
||||
Given $n$ types of coins, where the denomination of the $i$-th type of coin is $coins[i - 1]$, and the target amount is $amt$. **Each type of coin can be selected multiple times**. What is the minimum number of coins needed to make up the target amount? If it is impossible to make up the target amount, return $-1$. An example is shown in the figure below.
|
||||
Given $n$ coin denominations, where denomination $i$ has value $coins[i - 1]$, and a target amount $amt$, **each denomination may be used repeatedly**. What is the minimum number of coins needed to make the target? Return $-1$ if it cannot be made. An example is shown in the figure below.
|
||||
|
||||

|
||||

|
||||
|
||||
### Dynamic Programming Approach
|
||||
### Dynamic programming approach
|
||||
|
||||
**The coin change problem can be viewed as a special case of the unbounded knapsack problem**, with the following connections and differences.
|
||||
**Coin change can be viewed as a special case of unbounded knapsack**, with the following connections and differences.
|
||||
|
||||
- The two problems can be converted to each other: "item" corresponds to "coin", "item weight" corresponds to "coin denomination", and "knapsack capacity" corresponds to "target amount".
|
||||
- The optimization goals are opposite: the unbounded knapsack problem aims to maximize item value, while the coin change problem aims to minimize the number of coins.
|
||||
- The unbounded knapsack problem seeks solutions "not exceeding" the knapsack capacity, while the coin change problem seeks solutions that "exactly" make up the target amount.
|
||||
- The two problems can be translated into one another: items correspond to coins, item weights to coin denominations, and knapsack capacity to the target amount.
|
||||
- The optimization objectives are opposite: unbounded knapsack maximizes item value, while coin change minimizes the number of coins.
|
||||
- Unbounded knapsack must stay within a capacity limit, whereas coin change must reach the target amount exactly.
|
||||
|
||||
**Step 1: Think about the decisions in each round, define the state, and thus obtain the $dp$ table**
|
||||
**Step 1: Identify each decision, define the state, and establish the $dp$ table**
|
||||
|
||||
State $[i, a]$ corresponds to the subproblem: **the minimum number of coins among the first $i$ types of coins that can make up amount $a$**, denoted as $dp[i, a]$.
|
||||
State $[i, a]$ represents the subproblem of finding **the minimum number of coins needed to make amount $a$ using the first $i$ denominations**, denoted by $dp[i, a]$.
|
||||
|
||||
The two-dimensional $dp$ table has size $(n+1) \times (amt+1)$.
|
||||
|
||||
**Step 2: Identify the optimal substructure, and then derive the state transition equation**
|
||||
**Step 2: Identify optimal substructure and derive the state transition equation**
|
||||
|
||||
This problem differs from the unbounded knapsack problem in the following two aspects regarding the state transition equation.
|
||||
The state transition differs from unbounded knapsack in two ways.
|
||||
|
||||
- This problem seeks the minimum value, so the operator $\max()$ needs to be changed to $\min()$.
|
||||
- The optimization target is the number of coins rather than item value, so when a coin is selected, simply add $1$.
|
||||
- We want a minimum, so replace $\max()$ with $\min()$.
|
||||
- We optimize the coin count rather than item value, so choosing a coin adds $+1$.
|
||||
|
||||
$$
|
||||
dp[i, a] = \min(dp[i-1, a], dp[i, a - coins[i-1]] + 1)
|
||||
$$
|
||||
|
||||
**Step 3: Determine boundary conditions and state transition order**
|
||||
**Step 3: Determine the boundary conditions and evaluation order**
|
||||
|
||||
When the target amount is $0$, the minimum number of coins needed to make it up is $0$, so all $dp[i, 0]$ in the first column equal $0$.
|
||||
A target amount of $0$ requires $0$ coins, so every entry $dp[i, 0]$ in the first column is $0$.
|
||||
|
||||
When there are no coins, **it is impossible to make up any amount $> 0$**, which is an invalid solution. To enable the $\min()$ function in the state transition equation to identify and filter out invalid solutions, we consider using $+ \infty$ to represent them, i.e., set all $dp[0, a]$ in the first row to $+ \infty$.
|
||||
With no coins, **any target amount $> 0$ is impossible**. To let $\min()$ recognize and discard these infeasible solutions, represent them by $+ \infty$: set the first-row entries $dp[0, a]$ to $+ \infty$.
|
||||
|
||||
### Code Implementation
|
||||
### Code implementation
|
||||
|
||||
Most programming languages do not provide a $+ \infty$ variable, and can only use the maximum value of integer type `int` as a substitute. However, this can lead to integer overflow: the $+ 1$ operation in the state transition equation may cause overflow.
|
||||
Most programming languages do not provide an integer value for $+ \infty$, so the maximum `int` value is used instead. However, the $+ 1$ in the transition may then overflow.
|
||||
|
||||
For this reason, we use the number $amt + 1$ to represent invalid solutions, because the maximum number of coins needed to make up $amt$ is at most $amt$. Before returning, check whether $dp[n, amt]$ equals $amt + 1$; if so, return $-1$, indicating that the target amount cannot be made up. The code is as follows:
|
||||
Instead, use $amt + 1$ to represent an infeasible solution, since making $amt$ requires at most $amt$ coins. Before returning, check whether $dp[n, amt]$ equals $amt + 1$. If so, return $-1$ to indicate that the target cannot be made. The code is as follows:
|
||||
|
||||
```src
|
||||
[file]{coin_change}-[class]{}-[func]{coin_change_dp}
|
||||
```
|
||||
|
||||
The figure below shows the dynamic programming process for coin change, which is very similar to the unbounded knapsack problem.
|
||||
The figure below shows dynamic programming for coin change, which closely resembles unbounded knapsack.
|
||||
|
||||
=== "<1>"
|
||||

|
||||

|
||||
|
||||
=== "<2>"
|
||||

|
||||
@@ -164,43 +164,43 @@ The figure below shows the dynamic programming process for coin change, which is
|
||||
=== "<15>"
|
||||

|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
The space optimization for the coin change problem is handled in the same way as the unbounded knapsack problem:
|
||||
Space optimization is the same as for unbounded knapsack:
|
||||
|
||||
```src
|
||||
[file]{coin_change}-[class]{}-[func]{coin_change_dp_comp}
|
||||
```
|
||||
|
||||
## Coin Change Problem II
|
||||
## Coin change problem II
|
||||
|
||||
!!! question
|
||||
|
||||
Given $n$ types of coins, where the denomination of the $i$-th type of coin is $coins[i - 1]$, and the target amount is $amt$. Each type of coin can be selected multiple times. **What is the number of coin combinations that can make up the target amount?** An example is shown in the figure below.
|
||||
Given $n$ coin denominations, where denomination $i$ has value $coins[i - 1]$, and a target amount $amt$, each denomination may be used repeatedly. **How many combinations of coins make the target amount**? An example is shown in the figure below.
|
||||
|
||||

|
||||

|
||||
|
||||
### Dynamic Programming Approach
|
||||
### Dynamic programming approach
|
||||
|
||||
Compared to the previous problem, this problem's goal is to find the number of combinations, so the subproblem becomes: **the number of combinations among the first $i$ types of coins that can make up amount $a$**. The $dp$ table remains a two-dimensional matrix of size $(n+1) \times (amt + 1)$.
|
||||
This time, we count combinations, so the subproblem becomes **the number of combinations that make amount $a$ using the first $i$ denominations**. The $dp$ table remains a two-dimensional matrix of size $(n+1) \times (amt + 1)$.
|
||||
|
||||
The number of combinations for the current state equals the sum of the combinations from not selecting the current coin and selecting the current coin. The state transition equation is:
|
||||
The number of combinations for the current state is the sum of those that exclude the current coin and those that include it. The state transition equation is:
|
||||
|
||||
$$
|
||||
dp[i, a] = dp[i-1, a] + dp[i, a - coins[i-1]]
|
||||
$$
|
||||
|
||||
When the target amount is $0$, no coins need to be selected to make up the target amount, so all $dp[i, 0]$ in the first column should be initialized to $1$. When there are no coins, it is impossible to make up any amount $>0$, so all $dp[0, a]$ in the first row equal $0$.
|
||||
A target of $0$ can be made by choosing no coins, so initialize every first-column entry $dp[i, 0]$ to $1$. With no coins, any target $>0$ is impossible, so the first-row entries $dp[0, a]$ are $0$.
|
||||
|
||||
### Code Implementation
|
||||
### Code implementation
|
||||
|
||||
```src
|
||||
[file]{coin_change_ii}-[class]{}-[func]{coin_change_ii_dp}
|
||||
```
|
||||
|
||||
### Space Optimization
|
||||
### Space optimization
|
||||
|
||||
The space optimization is handled in the same way, just delete the coin dimension:
|
||||
The space optimization is the same: remove the coin dimension:
|
||||
|
||||
```src
|
||||
[file]{coin_change_ii}-[class]{}-[func]{coin_change_ii_dp_comp}
|
||||
|
||||
Reference in New Issue
Block a user