From recursion to the table
You already know memoization from the Complexity lesson: storing the results of a recursive function to avoid repeating…
When a problem is made of subproblems that repeat, storing each answer only once turns impossible solutions into fast ones. In this lesson you will go from recursion with memoization to tables, and solve classic problems: the house robber, the knapsack, making change, subsequences, the minimum cost path on a grid and the edit distance between strings.
You already know memoization from the Complexity lesson: storing the results of a recursive function to avoid repeating…
The simplest case is when the state is a single number: an amount, a position… The table is a list and each cell is computed from…
In the 0/1 knapsack each item is either taken whole or not taken. The state is the capacity that is left; for each item you…
When the problem lives on a grid or a triangle, the state is the coordinates (i, j) . If you can only move right and down, each…
With two strings the state is usually (i, j) : the first i characters of one and the first j of the other. That is how the…
A street has houses with money and you cannot rob two adjacent houses . At each house you decide: rob it (adding to what you had…
You have a knapsack with limited capacity and items with weight and value. Each item is taken whole or not at all . The table…
A subsequence is obtained by deleting characters without changing the order of the others (they need not be contiguous). With a…
The edit distance (Levenshtein) is the smallest number of operations to turn one string into another, where each operation is…
For each position you compute the length of the longest strictly increasing subsequence ending there, looking at all earlier…
In a grid with a cost on each square you go from the top left corner to the bottom right one moving only right or down . The best…
In how many different ways can an amount be formed with coins of certain values, with as many coins of each as you want? Here…
Can a list of numbers be split into two groups with the same sum ? It is the subset sum problem: you look for a subset that adds…
In a triangle of numbers you go from the top to the base and at each step you move to one of the two adjacent numbers in the row…
Given a string without spaces and a set of words, can the string be split into a sequence of words from the set (each may be…