Skip to content

14.2   Properties of dynamic programming problems

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 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.

Dynamic programming is often used for optimization problems. Besides overlapping subproblems, these problems have two key properties: optimal substructure and the no-aftereffect property.

14.2.1   Optimal substructure

Let's modify the climbing stairs problem slightly to illustrate optimal substructure more clearly.

Minimum cost to climb stairs

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 Figure 14-6, if steps \(1\), \(2\), and \(3\) cost \(1\), \(10\), and \(1\), respectively, the minimum cost of reaching step \(3\) from the ground is \(2\).

Figure 14-6   Minimum cost of reaching step 3

Description of Figure 14-6: Minimum cost to climb a three-step staircase

With costs 0, 1, 10, and 1 on the ground and steps 1 through 3, stepping over cost-10 step 2 along 0→1→3 achieves the minimum total cost of 2.

Each move climbs 1 or 2 steps and pays the cost of every step landed on; the figure labels step numbers as n and step costs as cost[n]. Ground start has cost[0] = 0, and the goal is to land on step 3 and pay step 3's cost.

Aligned beneath the staircase are step numbers n = 0, 1, 2, 3 and costs cost[n] = 0, 1, 10, 1, with step 2's tread and cost 10 highlighted in red and target step 3's tread highlighted in green. Above the steps, a solid cyan curve traces 0→1→2→3, a blue dotted curve traces 0→2→3, and an orange dashed curve traces 0→1→3. The bottom note states that among these 3 routes, 0→1→3 has the minimum cost of 2.

Single-step costs in the table below come from cost in the figure, while the sums and totals 12 and 11 are computed by adding the steps visited rather than printed in the figure.

Costs of the three routes (computed from cost in the figure)
RouteCost calculationTotal cost
0→1→2→31+10+112
0→2→310+111
0→1→31+12

Both of the first two routes land on step 2 of cost 10; only 0→1→3 steps over it, achieving the lowest total cost.

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 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: choose the better of \(dp[i-1]\) and \(dp[i-2]\) and use it to construct the optimal solution \(dp[i]\).

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.

The state transition equation, together with the initial states \(dp[1] = cost[1]\) and \(dp[2] = cost[2]\), gives the following dynamic programming code:

min_cost_climbing_stairs_dp.py
def min_cost_climbing_stairs_dp(cost: list[int]) -> int:
    """Minimum cost to climb stairs: dynamic programming"""
    n = len(cost) - 1
    if n == 1 or n == 2:
        return cost[n]
    # Initialize the dp table to store subproblem solutions
    dp = [0] * (n + 1)
    # Initial states: set the solutions to the smallest subproblems
    dp[1], dp[2] = cost[1], cost[2]
    # State transitions: solve progressively larger subproblems using smaller ones
    for i in range(3, n + 1):
        dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
    return dp[n]
min_cost_climbing_stairs_dp.cpp
/* Minimum cost to climb stairs: dynamic programming */
int minCostClimbingStairsDP(vector<int> &cost) {
    int n = cost.size() - 1;
    if (n == 1 || n == 2)
        return cost[n];
    // Initialize the dp table to store subproblem solutions
    vector<int> dp(n + 1);
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    return dp[n];
}
min_cost_climbing_stairs_dp.java
/* Minimum cost to climb stairs: dynamic programming */
int minCostClimbingStairsDP(int[] cost) {
    int n = cost.length - 1;
    if (n == 1 || n == 2)
        return cost[n];
    // Initialize the dp table to store subproblem solutions
    int[] dp = new int[n + 1];
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    return dp[n];
}
min_cost_climbing_stairs_dp.cs
/* Minimum cost to climb stairs: dynamic programming */
int MinCostClimbingStairsDP(int[] cost) {
    int n = cost.Length - 1;
    if (n == 1 || n == 2)
        return cost[n];
    // Initialize the dp table to store subproblem solutions
    int[] dp = new int[n + 1];
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    return dp[n];
}
min_cost_climbing_stairs_dp.go
/* Minimum cost to climb stairs: dynamic programming */
func minCostClimbingStairsDP(cost []int) int {
    n := len(cost) - 1
    if n == 1 || n == 2 {
        return cost[n]
    }
    min := func(a, b int) int {
        if a < b {
            return a
        }
        return b
    }
    // Initialize the dp table to store subproblem solutions
    dp := make([]int, n+1)
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1]
    dp[2] = cost[2]
    // State transitions: solve progressively larger subproblems using smaller ones
    for i := 3; i <= n; i++ {
        dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
    }
    return dp[n]
}
min_cost_climbing_stairs_dp.swift
/* Minimum cost to climb stairs: dynamic programming */
func minCostClimbingStairsDP(cost: [Int]) -> Int {
    let n = cost.count - 1
    if n == 1 || n == 2 {
        return cost[n]
    }
    // Initialize the dp table to store subproblem solutions
    var dp = Array(repeating: 0, count: n + 1)
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1]
    dp[2] = cost[2]
    // State transitions: solve progressively larger subproblems using smaller ones
    for i in 3 ... n {
        dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
    }
    return dp[n]
}
min_cost_climbing_stairs_dp.js
/* Minimum cost to climb stairs: dynamic programming */
function minCostClimbingStairsDP(cost) {
    const n = cost.length - 1;
    if (n === 1 || n === 2) {
        return cost[n];
    }
    // Initialize the dp table to store subproblem solutions
    const dp = new Array(n + 1);
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (let i = 3; i <= n; i++) {
        dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    return dp[n];
}
min_cost_climbing_stairs_dp.ts
/* Minimum cost to climb stairs: dynamic programming */
function minCostClimbingStairsDP(cost: Array<number>): number {
    const n = cost.length - 1;
    if (n === 1 || n === 2) {
        return cost[n];
    }
    // Initialize the dp table to store subproblem solutions
    const dp = new Array(n + 1);
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (let i = 3; i <= n; i++) {
        dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    return dp[n];
}
min_cost_climbing_stairs_dp.dart
/* Minimum cost to climb stairs: dynamic programming */
int minCostClimbingStairsDP(List<int> cost) {
  int n = cost.length - 1;
  if (n == 1 || n == 2) return cost[n];
  // Initialize the dp table to store subproblem solutions
  List<int> dp = List.filled(n + 1, 0);
  // Initial states: set the solutions to the smallest subproblems
  dp[1] = cost[1];
  dp[2] = cost[2];
  // State transitions: solve progressively larger subproblems using smaller ones
  for (int i = 3; i <= n; i++) {
    dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
  }
  return dp[n];
}
min_cost_climbing_stairs_dp.rs
/* Minimum cost to climb stairs: dynamic programming */
fn min_cost_climbing_stairs_dp(cost: &[i32]) -> i32 {
    let n = cost.len() - 1;
    if n == 1 || n == 2 {
        return cost[n];
    }
    // Initialize the dp table to store subproblem solutions
    let mut dp = vec![-1; n + 1];
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for i in 3..=n {
        dp[i] = cmp::min(dp[i - 1], dp[i - 2]) + cost[i];
    }
    dp[n]
}
min_cost_climbing_stairs_dp.c
/* Minimum cost to climb stairs: dynamic programming */
int minCostClimbingStairsDP(int cost[], int costSize) {
    int n = costSize - 1;
    if (n == 1 || n == 2)
        return cost[n];
    // Initialize the dp table to store subproblem solutions
    int *dp = calloc(n + 1, sizeof(int));
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1];
    dp[2] = cost[2];
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i] = myMin(dp[i - 1], dp[i - 2]) + cost[i];
    }
    int res = dp[n];
    // Free memory
    free(dp);
    return res;
}
min_cost_climbing_stairs_dp.kt
/* Minimum cost to climb stairs: dynamic programming */
fun minCostClimbingStairsDP(cost: IntArray): Int {
    val n = cost.size - 1
    if (n == 1 || n == 2) return cost[n]
    // Initialize the dp table to store subproblem solutions
    val dp = IntArray(n + 1)
    // Initial states: set the solutions to the smallest subproblems
    dp[1] = cost[1]
    dp[2] = cost[2]
    // State transitions: solve progressively larger subproblems using smaller ones
    for (i in 3..n) {
        dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
    }
    return dp[n]
}
min_cost_climbing_stairs_dp.rb
### Minimum cost to climb stairs: dynamic programming ###
def min_cost_climbing_stairs_dp(cost)
  n = cost.length - 1
  return cost[n] if n == 1 || n == 2
  # Initialize the dp table to store subproblem solutions
  dp = Array.new(n + 1, 0)
  # Initial states: set the solutions to the smallest subproblems
  dp[1], dp[2] = cost[1], cost[2]
  # State transitions: solve progressively larger subproblems using smaller ones
  (3...(n + 1)).each { |i| dp[i] = [dp[i - 1], dp[i - 2]].min + cost[i] }
  dp[n]
end
Visualize execution

Figure 14-7 illustrates this dynamic programming process.

Figure 14-7   Dynamic programming for the minimum climbing cost

Description of Figure 14-7: State transitions for minimum climbing cost

Each state takes the smaller cumulative minimum cost of its two predecessors and adds cost[i], the cost of the current step.

Each move climbs 1 or 2 steps, cost[i] is the nonnegative cost paid upon landing on step i, and starting on the ground is free. Let dp[i] denote the minimum cumulative cost to reach step i.

Green blocks dp[1] through dp[9] run horizontally from left to right; odd-indexed cost labels sit above and even-indexed ones sit below, pointing into their respective dp blocks. States dp[1] and dp[2] receive only their own cost arrows; starting at dp[3], brackets and min markers combine the two preceding states into the next state, with a plus sign beside the incoming cost arrow for paying the current step's cost. Below the diagram appear the initial states and general recurrence dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i] without concrete cost numbers.

The final move onto step i must come from either step i - 1 or step i - 2. Because landing on step i pays cost[i] regardless of predecessor, compare predecessor costs dp[i - 1] and dp[i - 2] to pick the smaller cumulative cost and then add cost[i].

From the ground one can step directly onto step 1 or step 2, giving dp[1] = cost[1]. Because cost[1] is nonnegative, passing through step 1 on the way to step 2 can never cost less than stepping straight onto step 2, so dp[2] = cost[2]. The table below lists steps 1 through 9 individually for lookup; the "Ground" origin and "no worse than via step 1" notes are supplied from the problem rules rather than a separate ground node drawn in the figure.

Initial values and predecessor comparisons
StateInitial source or compared predecessorsCost paid at stepFormula
dp[1]Groundcost[1]dp[1] = cost[1]
dp[2]Two-step jump directly from ground (no worse than via step 1)cost[2]dp[2] = cost[2]
dp[3]dp[2] or dp[1]cost[3]min(dp[2], dp[1]) + cost[3]
dp[4]dp[3] or dp[2]cost[4]min(dp[3], dp[2]) + cost[4]
dp[5]dp[4] or dp[3]cost[5]min(dp[4], dp[3]) + cost[5]
dp[6]dp[5] or dp[4]cost[6]min(dp[5], dp[4]) + cost[6]
dp[7]dp[6] or dp[5]cost[7]min(dp[6], dp[5]) + cost[7]
dp[8]dp[7] or dp[6]cost[8]min(dp[7], dp[6]) + cost[8]
dp[9]dp[8] or dp[7]cost[9]min(dp[8], dp[7]) + cost[9]

Evaluating sequentially up to the target step yields the minimum cumulative cost in that step's dp entry.

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)\):

min_cost_climbing_stairs_dp.py
def min_cost_climbing_stairs_dp_comp(cost: list[int]) -> int:
    """Minimum cost to climb stairs: space-optimized dynamic programming"""
    n = len(cost) - 1
    if n == 1 or n == 2:
        return cost[n]
    a, b = cost[1], cost[2]
    for i in range(3, n + 1):
        a, b = b, min(a, b) + cost[i]
    return b
min_cost_climbing_stairs_dp.cpp
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int minCostClimbingStairsDPComp(vector<int> &cost) {
    int n = cost.size() - 1;
    if (n == 1 || n == 2)
        return cost[n];
    int a = cost[1], b = cost[2];
    for (int i = 3; i <= n; i++) {
        int tmp = b;
        b = min(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.java
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int minCostClimbingStairsDPComp(int[] cost) {
    int n = cost.length - 1;
    if (n == 1 || n == 2)
        return cost[n];
    int a = cost[1], b = cost[2];
    for (int i = 3; i <= n; i++) {
        int tmp = b;
        b = Math.min(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.cs
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int MinCostClimbingStairsDPComp(int[] cost) {
    int n = cost.Length - 1;
    if (n == 1 || n == 2)
        return cost[n];
    int a = cost[1], b = cost[2];
    for (int i = 3; i <= n; i++) {
        int tmp = b;
        b = Math.Min(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.go
/* Minimum cost to climb stairs: space-optimized dynamic programming */
func minCostClimbingStairsDPComp(cost []int) int {
    n := len(cost) - 1
    if n == 1 || n == 2 {
        return cost[n]
    }
    min := func(a, b int) int {
        if a < b {
            return a
        }
        return b
    }
    // Initial states: set the solutions to the smallest subproblems
    a, b := cost[1], cost[2]
    // State transitions: solve progressively larger subproblems using smaller ones
    for i := 3; i <= n; i++ {
        tmp := b
        b = min(a, tmp) + cost[i]
        a = tmp
    }
    return b
}
min_cost_climbing_stairs_dp.swift
/* Minimum cost to climb stairs: space-optimized dynamic programming */
func minCostClimbingStairsDPComp(cost: [Int]) -> Int {
    let n = cost.count - 1
    if n == 1 || n == 2 {
        return cost[n]
    }
    var (a, b) = (cost[1], cost[2])
    for i in 3 ... n {
        (a, b) = (b, min(a, b) + cost[i])
    }
    return b
}
min_cost_climbing_stairs_dp.js
/* Minimum cost to climb stairs: space-optimized dynamic programming */
function minCostClimbingStairsDPComp(cost) {
    const n = cost.length - 1;
    if (n === 1 || n === 2) {
        return cost[n];
    }
    let a = cost[1],
        b = cost[2];
    for (let i = 3; i <= n; i++) {
        const tmp = b;
        b = Math.min(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.ts
/* Minimum cost to climb stairs: space-optimized dynamic programming */
function minCostClimbingStairsDPComp(cost: Array<number>): number {
    const n = cost.length - 1;
    if (n === 1 || n === 2) {
        return cost[n];
    }
    let a = cost[1],
        b = cost[2];
    for (let i = 3; i <= n; i++) {
        const tmp = b;
        b = Math.min(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.dart
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int minCostClimbingStairsDPComp(List<int> cost) {
  int n = cost.length - 1;
  if (n == 1 || n == 2) return cost[n];
  int a = cost[1], b = cost[2];
  for (int i = 3; i <= n; i++) {
    int tmp = b;
    b = min(a, tmp) + cost[i];
    a = tmp;
  }
  return b;
}
min_cost_climbing_stairs_dp.rs
/* Minimum cost to climb stairs: space-optimized dynamic programming */
fn min_cost_climbing_stairs_dp_comp(cost: &[i32]) -> i32 {
    let n = cost.len() - 1;
    if n == 1 || n == 2 {
        return cost[n];
    };
    let (mut a, mut b) = (cost[1], cost[2]);
    for i in 3..=n {
        let tmp = b;
        b = cmp::min(a, tmp) + cost[i];
        a = tmp;
    }
    b
}
min_cost_climbing_stairs_dp.c
/* Minimum cost to climb stairs: space-optimized dynamic programming */
int minCostClimbingStairsDPComp(int cost[], int costSize) {
    int n = costSize - 1;
    if (n == 1 || n == 2)
        return cost[n];
    int a = cost[1], b = cost[2];
    for (int i = 3; i <= n; i++) {
        int tmp = b;
        b = myMin(a, tmp) + cost[i];
        a = tmp;
    }
    return b;
}
min_cost_climbing_stairs_dp.kt
/* Minimum cost to climb stairs: space-optimized dynamic programming */
fun minCostClimbingStairsDPComp(cost: IntArray): Int {
    val n = cost.size - 1
    if (n == 1 || n == 2) return cost[n]
    var a = cost[1]
    var b = cost[2]
    for (i in 3..n) {
        val tmp = b
        b = min(a, tmp) + cost[i]
        a = tmp
    }
    return b
}
min_cost_climbing_stairs_dp.rb
### Minimum cost to climb stairs: space-optimized dynamic programming ###
def min_cost_climbing_stairs_dp_comp(cost)
  n = cost.length - 1
  return cost[n] if n == 1 || n == 2
  a, b = cost[1], cost[2]
  (3...(n + 1)).each { |i| a, b = b, [a, b].min + cost[i] }
  b
end
Visualize execution

14.2.2   No-aftereffect property

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.

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\).

Adding a constraint changes the situation.

Climbing stairs with a constraint

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 Figure 14-8, only \(2\) ways remain to reach step \(3\): taking \(1\) step three times in a row violates the constraint and is discarded.

Figure 14-8   Number of ways to reach step 3 with the constraint

Description of Figure 14-8: Ways to reach step 3 when two consecutive 1-step moves are forbidden

Adding the constraint against two consecutive 1-step moves discards 0→1→2→3, leaving 2 valid ways to reach step 3.

Starting from ground level 0, each move may still climb 1 or 2 steps toward target step 3, under the added constraint that two consecutive moves may not both climb 1 step.

The staircase labels steps 0 through 6 with target step 3 shaded green. Route 0→1→2→3 is drawn as a gray dotted curve with the callout above "Because two consecutive one-step moves are forbidden, the route 0 → 1 → 2 → 3 is discarded"; the solid blue curve 0→2→3 and solid orange curve 0→1→3 remain highlighted, and the bottom caption reads "There are 2 ways to reach step 3: 0 → 2 → 3, 0 → 1 → 3".

Route 0→1→2→3 takes three consecutive 1-step moves, violating the ban on two consecutive 1-step moves in its very first two moves, so it is grayed out and discarded. Blue route 0→2→3 climbs 2 steps then 1 step, and orange route 0→1→3 climbs 1 step then 2 steps; neither contains adjacent 1-step moves, so both remain valid.

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).

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.

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.

  • 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 Figure 14-9, \(dp[i, j]\) now counts the ways to reach state \([i, j]\). The state transition equations are:

\[ \begin{cases} dp[i, 1] = dp[i-1, 2] \\ dp[i, 2] = dp[i-2, 1] + dp[i-2, 2] \end{cases} \]

Figure 14-9   Recurrence with the constraint

Description of Figure 14-9: Extending the dynamic programming state with the previous step size

Recording whether the last move climbed 1 or 2 steps in the two-dimensional state dp[i, j] excludes consecutive 1-step moves during transitions.

Each move climbs 1 or 2 steps, with two consecutive 1-step moves forbidden. Because whether a 1-step move is currently allowed depends on the previous step size, extend the state to two-dimensional dp[i, j]: the number of ways to reach step i whose last move climbed j steps (for j = 1 or 2).

On the top step, the figure labels two target states: cyan dp[i, 1] and blue dp[i, 2]; on step i - 1, cyan dp[i - 1, 2] and gray dp[i - 1, 1]; and on step i - 2, blue dp[i - 2, 1] and blue dp[i - 2, 2]. A solid cyan arc spans 1 step from dp[i - 1, 2] to dp[i, 1], whereas a gray dotted arc from gray dp[i - 1, 1] to dp[i, 1] carries the note "Two consecutive one-step moves are forbidden, so this term is discarded"; from dp[i - 2, 1] and dp[i - 2, 2], two solid blue arcs each span 2 steps into dp[i, 2].

When the final move climbs 1 step from step i - 1, the move that reached step i - 1 must have climbed 2 steps, giving dp[i, 1] = dp[i - 1, 2]. When the final move climbs 2 steps from step i - 2, the move that reached step i - 2 could have climbed either 1 or 2 steps, giving dp[i, 2] = dp[i - 2, 1] + dp[i - 2, 2].

The figure draws only symbolic transitions without numeric initial values. The table below supplies the initial states at steps 1 and 2 from the chapter code, from which recurrence begins at step 3.

Initial states in the chapter code (supplied base cases)
Step idp[i,1]dp[i,2]
110
201

Step 1 has only 0→1, so dp[1, 1] = 1 and dp[1, 2] = 0. For step 2, 0→1→2 takes two consecutive 1-step moves and is invalid; only 0→2 is valid, so dp[2, 1] = 0 and dp[2, 2] = 1.

Once the state includes the last move's step size, valid subsequent moves depend only on the current state, restoring the no-aftereffect property; the total number of ways to reach step n is dp[n, 1] + dp[n, 2].

Finally, return \(dp[n, 1] + dp[n, 2]\), the total number of ways to reach step \(n\):

climbing_stairs_constraint_dp.py
def climbing_stairs_constraint_dp(n: int) -> int:
    """Climbing stairs with constraints: dynamic programming"""
    if n == 1 or n == 2:
        return 1
    # Initialize the dp table to store subproblem solutions
    dp = [[0] * 3 for _ in range(n + 1)]
    # Initial states: set the solutions to the smallest subproblems
    dp[1][1], dp[1][2] = 1, 0
    dp[2][1], dp[2][2] = 0, 1
    # State transitions: solve progressively larger subproblems using smaller ones
    for i in range(3, n + 1):
        dp[i][1] = dp[i - 1][2]
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
    return dp[n][1] + dp[n][2]
climbing_stairs_constraint_dp.cpp
/* Climbing stairs with constraints: dynamic programming */
int climbingStairsConstraintDP(int n) {
    if (n == 1 || n == 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    vector<vector<int>> dp(n + 1, vector<int>(3, 0));
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    return dp[n][1] + dp[n][2];
}
climbing_stairs_constraint_dp.java
/* Climbing stairs with constraints: dynamic programming */
int climbingStairsConstraintDP(int n) {
    if (n == 1 || n == 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    int[][] dp = new int[n + 1][3];
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    return dp[n][1] + dp[n][2];
}
climbing_stairs_constraint_dp.cs
/* Climbing stairs with constraints: dynamic programming */
int ClimbingStairsConstraintDP(int n) {
    if (n == 1 || n == 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    int[,] dp = new int[n + 1, 3];
    // Initial states: set the solutions to the smallest subproblems
    dp[1, 1] = 1;
    dp[1, 2] = 0;
    dp[2, 1] = 0;
    dp[2, 2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i, 1] = dp[i - 1, 2];
        dp[i, 2] = dp[i - 2, 1] + dp[i - 2, 2];
    }
    return dp[n, 1] + dp[n, 2];
}
climbing_stairs_constraint_dp.go
/* Climbing stairs with constraints: dynamic programming */
func climbingStairsConstraintDP(n int) int {
    if n == 1 || n == 2 {
        return 1
    }
    // Initialize the dp table to store subproblem solutions
    dp := make([][3]int, n+1)
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1
    dp[1][2] = 0
    dp[2][1] = 0
    dp[2][2] = 1
    // State transitions: solve progressively larger subproblems using smaller ones
    for i := 3; i <= n; i++ {
        dp[i][1] = dp[i-1][2]
        dp[i][2] = dp[i-2][1] + dp[i-2][2]
    }
    return dp[n][1] + dp[n][2]
}
climbing_stairs_constraint_dp.swift
/* Climbing stairs with constraints: dynamic programming */
func climbingStairsConstraintDP(n: Int) -> Int {
    if n == 1 || n == 2 {
        return 1
    }
    // Initialize the dp table to store subproblem solutions
    var dp = Array(repeating: Array(repeating: 0, count: 3), count: n + 1)
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1
    dp[1][2] = 0
    dp[2][1] = 0
    dp[2][2] = 1
    // State transitions: solve progressively larger subproblems using smaller ones
    for i in 3 ... n {
        dp[i][1] = dp[i - 1][2]
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
    }
    return dp[n][1] + dp[n][2]
}
climbing_stairs_constraint_dp.js
/* Climbing stairs with constraints: dynamic programming */
function climbingStairsConstraintDP(n) {
    if (n === 1 || n === 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    const dp = Array.from(new Array(n + 1), () => new Array(3));
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (let i = 3; i <= n; i++) {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    return dp[n][1] + dp[n][2];
}
climbing_stairs_constraint_dp.ts
/* Climbing stairs with constraints: dynamic programming */
function climbingStairsConstraintDP(n: number): number {
    if (n === 1 || n === 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    const dp = Array.from({ length: n + 1 }, () => new Array(3));
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (let i = 3; i <= n; i++) {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    return dp[n][1] + dp[n][2];
}
climbing_stairs_constraint_dp.dart
/* Climbing stairs with constraints: dynamic programming */
int climbingStairsConstraintDP(int n) {
  if (n == 1 || n == 2) {
    return 1;
  }
  // Initialize the dp table to store subproblem solutions
  List<List<int>> dp = List.generate(n + 1, (index) => List.filled(3, 0));
  // Initial states: set the solutions to the smallest subproblems
  dp[1][1] = 1;
  dp[1][2] = 0;
  dp[2][1] = 0;
  dp[2][2] = 1;
  // State transitions: solve progressively larger subproblems using smaller ones
  for (int i = 3; i <= n; i++) {
    dp[i][1] = dp[i - 1][2];
    dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
  }
  return dp[n][1] + dp[n][2];
}
climbing_stairs_constraint_dp.rs
/* Climbing stairs with constraints: dynamic programming */
fn climbing_stairs_constraint_dp(n: usize) -> i32 {
    if n == 1 || n == 2 {
        return 1;
    };
    // Initialize the dp table to store subproblem solutions
    let mut dp = vec![vec![-1; 3]; n + 1];
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for i in 3..=n {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    dp[n][1] + dp[n][2]
}
climbing_stairs_constraint_dp.c
/* Climbing stairs with constraints: dynamic programming */
int climbingStairsConstraintDP(int n) {
    if (n == 1 || n == 2) {
        return 1;
    }
    // Initialize the dp table to store subproblem solutions
    int **dp = malloc((n + 1) * sizeof(int *));
    for (int i = 0; i <= n; i++) {
        dp[i] = calloc(3, sizeof(int));
    }
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1;
    dp[1][2] = 0;
    dp[2][1] = 0;
    dp[2][2] = 1;
    // State transitions: solve progressively larger subproblems using smaller ones
    for (int i = 3; i <= n; i++) {
        dp[i][1] = dp[i - 1][2];
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
    }
    int res = dp[n][1] + dp[n][2];
    // Free memory
    for (int i = 0; i <= n; i++) {
        free(dp[i]);
    }
    free(dp);
    return res;
}
climbing_stairs_constraint_dp.kt
/* Climbing stairs with constraints: dynamic programming */
fun climbingStairsConstraintDP(n: Int): Int {
    if (n == 1 || n == 2) {
        return 1
    }
    // Initialize the dp table to store subproblem solutions
    val dp = Array(n + 1) { IntArray(3) }
    // Initial states: set the solutions to the smallest subproblems
    dp[1][1] = 1
    dp[1][2] = 0
    dp[2][1] = 0
    dp[2][2] = 1
    // State transitions: solve progressively larger subproblems using smaller ones
    for (i in 3..n) {
        dp[i][1] = dp[i - 1][2]
        dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
    }
    return dp[n][1] + dp[n][2]
}
climbing_stairs_constraint_dp.rb
### Climbing stairs with constraints: dynamic programming ###
def climbing_stairs_constraint_dp(n)
  return 1 if n == 1 || n == 2

  # Initialize the dp table to store subproblem solutions
  dp = Array.new(n + 1) { Array.new(3, 0) }
  # Initial states: set the solutions to the smallest subproblems
  dp[1][1], dp[1][2] = 1, 0
  dp[2][1], dp[2][2] = 0, 1
  # State transitions: solve progressively larger subproblems using smaller ones
  for i in 3...(n + 1)
    dp[i][1] = dp[i - 1][2]
    dp[i][2] = dp[i - 2][1] + dp[i - 2][2]
  end

  dp[n][1] + dp[n][2]
end
Visualize execution

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.

Climbing stairs that generate obstacles

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?

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.

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.

Share your insights, questions, or suggestions in the comments