Dynamic Programming
Reuse overlapping subproblem answers to count step sequences.
python, dynamic programming, recurrence, stateSave answers to smaller questions
Suppose a path allows moves of one or two steps. The number of ways to
reach position i depends on answers for i - 1 and i - 2. Store those
answers instead of recalculating the same subproblems.
Python illustration
def count_ways(n):
if n < 0:
raise ValueError("n must be nonnegative")
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
ways[i] = ways[i - 1]
if i >= 2:
ways[i] += ways[i - 2]
return ways[n]
print(count_ways(4))
Prepared output: 5. The ordered sequences are 1+1+1+1, 1+1+2,
1+2+1, 2+1+1, and 2+2.
See the reasoning
Build the ways table
Use the two earlier counts at each position. This is a prepared demonstration, not live code execution.
Base case
- 01Current focus
- 1pending
- 2pending
- 3pending
- 4pending
One empty sequence reaches zero.
Define state before optimising
There is one empty sequence to reach zero. Every sequence to i ends in
either a one-step or two-step move; these disjoint cases give the recurrence.
For nonnegative integer n, the table has n + 1 states: O(n) additions and
O(n) stored integers. Python's arbitrary-size integers grow with the answer,
so bit-level time and memory are larger than a fixed-word model suggests.
Keeping only the last two values reduces the number of stored integers, but
would not directly retain the full table.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
