Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dynamic Programming

Dynamic Programming

Dynamic programming (English: Dynamic programming, abbreviated DP) is a method used in mathematics, management science, computer science, economics, and bioinformatics to solve complex problems by decomposing the original problem into relatively simpler subproblems.

Imagine you are climbing a n -level staircase. Each time you can climb 1 levels or 2 levels.

So, how many different ways are there to reach the top?

If you think from the top-level goal (the n level), it might seem complicated.

But if we change our thinking:To reach the n -level step, you can only reach it from the n-1 level by taking one step, or from the n-2 level by taking two steps. Therefore, the number of ways to reach the n level equals the number of ways to reach the n-1 level plus the number of ways to reach the n-2 level.

Thisbreaking a big problem into overlapping subproblems and avoiding recomputation by storing the solutions of subproblems, thereby efficiently solving the original problemis dynamic programming (Dynamic Programming, or DP for short).

Core idea

The core of dynamic programming is remembering the solutions already computed 。

Dynamic programming is typically used to solve problems with the following properties:

  1. Overlapping subproblems: during recursive solving, the same subproblem is computed many times.
  2. Optimal substructure: the optimal solution of a problem contains the optimal solutions of its subproblems.

We can use a simple flowchart to understand the problem-solving approach of dynamic programming:

The figure above shows the typical steps to solve a dynamic programming problem: start by defining the problem, find the subproblem structure through analysis, formalize it with states and state transition equations, and finally obtain the answer through clear initial conditions and computation order.


From Recursion to Dynamic Programming: The Climbing Stairs Problem

Let's use the classic "Climbing Stairs" problem to experience the optimization from recursion to dynamic programming.

Description

Suppose you are climbing a staircase. It takes n steps to reach the top. Each time you can climb 1 or 2 steps. How many distinct ways can you climb to the top?

Method 1: Brute-force Recursion (Inefficient)

Based on the analysis at the beginning, we can write the recursive formula directly: f(n) = f(n-1) + f(n-2) Where f(1) = 1, f(2) = 2。

Example

def

climb_stairs_recursive

(

n:

int

)

int

:

   

"""Recursive solution"""

   

if

n

==

1

:

       

return

1

   

if

n

==

2

:

       

return

2

   

return

climb_stairs_recursive

(

n -

1

)

(

n -

2

)

Testing

print

(

f

"Number of ways to reach step 5 (recursive): {climb_stairs_recursive(5)}"

)

 

Output: 8

Drawback analysis: this recursion involves a great deal of repeated computation. For example, computing f(5) Needed f(4) and f(3), computing f(4) also requires f(3) and f(2), where f(3) is computed twice. When n is large, the time complexity is exponential O(2^n), which is extremely inefficient.

Method 2: Recursion with Memoization (Top-down)

We can use an array ("memo") to store results that have already been computed and avoid repeated computation.

Example

def

climb_stairs_memo

(

n:

int

)

int

:

   

"""Recursion with memoization (top-down)"""

   

Initialize the memo, -1 means not yet computed

    memo

=

[

1

]

(

n +

1

)

   

   

def

helper

(

x:

int

)

int

:

       

Base cases

       

if

x

==

1

:

           

return

1

       

if

x

==

2

:

           

return

2

       

If already computed, return the result directly

       

if

memo

[

x

]

!=

1

:

           

return

memo

[

x

]

       

Otherwise, compute and store it in the memo

        memo

[

x

]

=

helper

(

x -

1

)

(

x -

2

)

       

return

memo

[

x

]

   

   

return

helper

(

n

)

print

(

f

"Number of ways to reach step 5 (memo): {climb_stairs_memo(5)}"

)

 

Output: 8

The time complexity of this approach drops to O(n), because each subproblem is computed only once. The space complexity is O(n). This is already a dynamic programming idea, called "top-down" or "memoized search"。

Method 3: Iterative Array (Bottom-up, Standard DP)

We start directly from the smallest subproblem and iterate step by step up to the original problem. Usually an array dp is used to store the states.

Example

def

climb_stairs_dp

(

n:

int

)

int

:

   

"""Dynamic programming (bottom-up)"""

   

if

n

<=

2

:

       

return

n

   

1. Define the state array: dp[i] is the number of ways to reach step i

    dp

=

[

0

]

(

n +

1

)

   

2. Determine the initial conditions

    dp

[

1

]

=

1

    dp

[

2

]

=

2

   

3. State transition: iterate according to the state transition equation

   

for

i

in

range

(

3

,

n +

1

)

:

        dp

[

i

]

=

dp

[

i -

1

]

[

i -

2

]

   

4. Return the final result

   

return

dp

[

n

]

print

(

f

"Number of ways to reach step 5 (DP): {climb_stairs_dp(5)}"

)

 

Output: 8

Method 4: Space Optimization (Rolling Array)

Observe the state transition equation dp[i] = dp[i-1] + dp[i-2], we find the current state depends only on the previous two states. Therefore, we do not need to store the entire dp array; just two variables with rolling updates suffice.

Example

def

climb_stairs_optimized

(

n:

int

)

int

:

   

"""Dynamic programming (space-optimized version)"""

   

if

n

<=

2

:

       

return

n

   

Use only two variables to represent dp[i-1] and dp[i-2]

    prev

,

curr

=

1

,

2

 

corresponding to dp[1], dp[2]

   

for

i

in

range

(

3

,

n +

1

)

:

       

Compute the new current value

        new_curr

=

prev + curr

       

Roll the variables forward to prepare for the next iteration

        prev

,

curr

=

curr

,

new_curr

   

return

curr

print

(

f

"Number of ways to reach step 5 (optimized DP): {climb_stairs_optimized(5)}"

)

 

Output: 8

After optimization, the space complexity drops from O(n) to O(1)。


Dynamic Programming Problem-Solving Framework

Through the climbing stairs problem, we can summarize a general four-step recipe for solving dynamic programming problems:

Step 1: Define the state

Use one or more arrays (usually called dp) to represent the solutions of subproblems. The key is to figure out what dp[i] or dp[i][j] represents.

In the climbing stairs problem, we define dp[i] as "the total number of ways to climb to step i ".

Step 2: Determine the state transition equation

Find the dp[i] relationship with previous states (such as dp[i-1], dp[i-2]). This is the core and the difficult part of dynamic programming.

In the climbing stairs problem, the state transition equation is: dp[i] = dp[i-1] + dp[i-2]。

Step 3: Determine the initial conditions (Base Case)

The solution of the smallest, indivisible subproblem. This is the starting point of the iteration and must be defined manually.

In the climbing stairs problem, the initial conditions are: dp[1] = 1, dp[2] = 2。

Step 4: Determine the computation order and compute

Decide whether to use "top-down" (memoized recursion) or "bottom-up" (iterative recursion), and ensure that when computing dp[i] , the subproblems it depends on have already been computed.

In the climbing stairs problem, we use bottom-up, looping from i=3 to i=n。


Classic Example: The Fibonacci Sequence

The Fibonacci sequence is the most direct example of dynamic programming; its definition itself is the state transition equation.

Problem: find the n terms of the Fibonacci sequence. F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) (n>=2)

Example

def

fibonacci

(

n:

int

)

int

:

   

"""Compute Fibonacci numbers with dynamic programming"""

   

if

n

<

2

:

       

return

n

   

Space-optimized version

    prev

,

curr

=

0

,

1

 

F(0), F(1)

   

for

_

in

range

(

2

,

n +

1

)

:

        prev

,

curr

=

curr

,

prev + curr

   

return

curr

Test Data

test_n

=

10

print

(

f

"The {test_n}-th Fibonacci number is: {fibonacci(test_n)}"

)

 

Output: 55


Advanced Example: Coin Change

This is a more typical problem that demonstrates optimal substructure.

Description: given an integer array coinsrepresenting coins of different denominations, and an integer amountrepresenting the total amount. Compute and return the minimum number of coins needed to make up the total amount. If no combination of coins can make up the amount, return -1. You may assume you have an unlimited supply of each coin.

Problem Analysis and DP Design

  1. Define the state:dp[i] represents the minimum number of coins needed to make up the total i amount.
  2. State transition equation: for amount i, we can iterate over each coin denomination coin. If coin <= i, then one possible way to make up the amount i is: first make up the amount i - coin, then add one coin -denomination coin. We want the minimum among all possibilities. Therefore, the equation can be written as: dp[i] = min(dp[i], dp[i - coin] + 1), for all satisfying coin <= i 's coin。
  3. Initial conditions:dp[0] = 0, making up amount 0 requires 0 coins. Other dp[i] values are initialized to a very large number (such as amount + 1 or float('inf')), representing temporarily unreachable.
  4. Computation order: bottom-up, computed from i=1 up to i=amount。

Code Implementation

Example

def

coin_change

(

coins:

list

,

amount:

int

)

int

:

   

"""Coin Change - Dynamic Programming"""

   

Initialize the dp array, dp[i] is the minimum number of coins for amount i

   

Set an unreachable initial value amount + 1

    dp

=

[

amount +

1

]

(

amount +

1

)

    dp

[

0

]

=

0

 

Amount 0 requires 0 coins

   

   

Outer loop: iterate over all amount states

   

for

i

in

range

(

1

,

amount +

1

)

:

       

Inner loop: iterate over all coin choices

       

for

coin

in

coins:

           

If the current coin value is no more than the current amount, consider using this coin

           

if

coin

<=

i:

               

State transition: dp[i] is the smaller of the solution without the current coin and

               

the solution using the current coin (i.e., dp[i-coin] + 1)

                dp

[

i

]

=

min

(

dp

[

i

]

,

dp

[

i - coin

]

1

)

   

   

If dp[amount] was not updated (still the initial value), it means the amount cannot be made up

   

return

dp

[

amount

]

if

dp

[

amount

]

<=

amount

else

1

Test Data

coins

=

[

1

,

2

,

5

]

amount

=

11

print

(

f

"The minimum number of coins to make up {amount} is: {coin_change(coins, amount)}"

)

 

Output: 3 (5+5+1)


Practical Exercise

Try to solve the following problems independently to reinforce your understanding of dynamic programming:

Exercise 1: Maximum Subarray Sum

Given an integer array nums, find a contiguous subarray with the largest sum and return that sum.

Example:

输入:nums = [-2,1,-3,4,-1,2,1,-5,4]

输出:6

解释:连续子数组 [4,-1,2,1] 的和最大,为 6。

Tip:

Exercise 2: Longest Increasing Subsequence

Given an integer array nums, find the length of its longest strictly increasing subsequence.

Example:

输入:nums = [10,9,2,5,3,7,101,18]

输出:4

解释:最长递增子序列是 [2,3,7,101],因此长度为 4。

Tip: