Dynamic programming
Solving problems by combining solutions to overlapping subproblems and storing them to avoid recomputation.
Edited by Alex C, EduAlx · Sources cited below
Explanation
Richard Bellman coined the term in the 1950s. It applies when a problem has optimal substructure and overlapping subproblems. Examples: Fibonacci, knapsack, longest common subsequence, sequence alignment (Needleman–Wunsch, Smith–Waterman) in bioinformatics.
Example
Code
from functools import lru_cache
@lru_cache(None)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
How it works, step by step
- Define the subproblem
- Write a recurrence
- Choose memoisation (top-down) or tabulation (bottom-up)
- Read the answer from the table
Open the interactive page with diagrams →
People behind it
- Richard Bellman
References
- R. Bellman, Dynamic Programming, Princeton University Press, 1957.
- S. B. Needleman, C. D. Wunsch, J. Mol. Biol. 1970, 48, 443–453.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
Related topics
Greedy algorithms and minimum spanning treesGraph algorithms: BFS, DFS and Dijkstra's shortest pathString algorithms and pattern matchingSorting algorithms (quicksort, mergesort, heapsort)Algorithms and Big-O complexityTuring machines and computabilityP versus NPTrees and binary search treesBoolean logic and digital circuitsHash tables