Study Atlas › Computer Science › Algorithms

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

Fibonacci with memoisation runs in O(n) instead of O(2ⁿ).

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

  1. Define the subproblem
  2. Write a recurrence
  3. Choose memoisation (top-down) or tabulation (bottom-up)
  4. Read the answer from the table

Open the interactive page with diagrams →

People behind it

References

  1. R. Bellman, Dynamic Programming, Princeton University Press, 1957.
  2. S. B. Needleman, C. D. Wunsch, J. Mol. Biol. 1970, 48, 443–453.

Textbooks

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