Dynamic programming

Answer the three questions first: what is the subproblem, how does it come from smaller ones, and what are the base cases. Write them as a comment at the top of your solution.

The lesson is Dynamic programming.

Cheapest way up the stairs

cost lists the price of stepping on each stair. You may start on stair 0 or stair 1 and climb one or two stairs at a time; you finish when you step past the last stair. Write min_cost(cost) that returns the cheapest total.

min_cost([10, 15, 20])                        ->  15
min_cost([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])  ->  6

The point is to practise a DP whose subproblem is "cheapest way to reach stair i".

def min_cost(cost):
    ...

Grid paths around obstacles

grid is a list of lists of 0 (open) and 1 (blocked). Write paths(grid) that returns how many routes go from the top-left to the bottom-right moving only right or down, never entering a blocked cell. If either corner is blocked the answer is 0.

paths([[0, 0, 0], [0, 1, 0], [0, 0, 0]])  ->  2
paths([[0, 1], [0, 0]])                   ->  1
paths([[1]])                              ->  0

The point is to practise a 2-D table where some cells are forced to zero.

def paths(grid):
    ...

Longest common subsequence

Write lcs(a, b) that returns the length of the longest sequence of characters that appears in both strings in the same order, not necessarily adjacent.

lcs("abcde", "ace")  ->  3
lcs("abc", "def")    ->  0
lcs("", "abc")       ->  0

The point is to practise a two-string DP table: table[i][j] for the first i characters of a and the first j of b.

def lcs(a, b):
    ...

Edit distance

Write edit_distance(a, b) that returns the fewest single-character insertions, deletions or replacements needed to turn a into b.

edit_distance("horse", "ros")          ->  3
edit_distance("intention", "execution")  ->  5
edit_distance("", "abc")               ->  3

The point is to practise a two-string table with three choices per cell.

def edit_distance(a, b):
    ...

Ways to make change

Write change_ways(amount, coins) that returns how many different combinations of the given coin denominations add up to amount. Order does not matter: 1+2 and 2+1 are the same combination. change_ways(0, coins) is 1.

change_ways(5, [1, 2, 5])  ->  4     (5, 2+2+1, 2+1+1+1, 1+1+1+1+1)
change_ways(3, [2])        ->  0
change_ways(10, [10])      ->  1

The point is to practise the loop order that counts combinations rather than sequences: coins outside, amounts inside.

def change_ways(amount, coins):
    ...

Longest increasing subsequence

Write lis(nums) that returns the length of the longest strictly increasing subsequence (not necessarily adjacent) of nums.

lis([10, 9, 2, 5, 3, 7, 101, 18])  ->  4     (2, 3, 7, 101)
lis([7, 7, 7])                     ->  1
lis([])                            ->  0

The point is to practise a DP where each subproblem looks back at all earlier ones. The quadratic version is fine here.

def lis(nums):
    ...

Ways to decode digits

Letters were encoded as numbers, A = 1 through Z = 26, and the digits concatenated. Write decode_ways(digits) that returns how many ways the digit string can be decoded. A 0 can only be part of 10 or 20.

decode_ways("12")   ->  2     (AB or L)
decode_ways("226")  ->  3     (BZ, VF, BBF)
decode_ways("06")   ->  0

The point is to practise a DP over string prefixes with two possible last steps.

def decode_ways(digits):
    ...

Can the text be split into words?

Write can_break(text, words) that returns whether text can be split into a sequence of words from the list words, with words reusable.

can_break("leetcode", ["leet", "code"])              ->  True
can_break("applepenapple", ["apple", "pen"])         ->  True
can_break("catsandog", ["cats", "dog", "sand", "and", "cat"])  ->  False

The point is to practise a DP over prefixes: a prefix is breakable if it ends with a word whose preceding prefix is breakable.

def can_break(text, words):
    ...

Split into two equal halves

Write can_split(nums) that returns whether the positive whole numbers in nums can be divided into two groups with equal sums.

can_split([1, 5, 11, 5])  ->  True     ([1, 5, 5] and [11])
can_split([1, 2, 3, 5])   ->  False

The point is to practise subset-sum DP: which totals can be made from some of the numbers?

def can_split(nums):
    ...

Knapsack

items is a list of (weight, value) pairs and the bag holds at most capacity weight. Each item can be taken once or not at all. Write best_value(items, capacity) that returns the largest total value that fits.

best_value([(1, 1), (3, 4), (4, 5), (5, 7)], 7)  ->  9     (3 + 4)
best_value([(5, 10)], 4)                        ->  0

The point is to practise the 0/1 knapsack table, the take-or-skip recurrence over capacities.

def best_value(items, capacity):
    ...

Cheapest path through a grid

grid is a list of lists of non-negative numbers. Write min_path(grid) that returns the smallest sum of values along a path from the top-left to the bottom-right moving only right or down.

min_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]])  ->  7
min_path([[1, 2], [1, 1]])                   ->  3

The point is to practise a 2-D DP with min instead of a sum of ways.

def min_path(grid):
    ...

Next: Backtracking.