One-dimensional Dynamic Programming
125 / 170One-dimensional Dynamic ProgrammingLesson 1 of 11About 89 min
The four-step ladder that every problem in this unit climbs, on a recurrence you have already met.
In Unit 10 you generated every binary string of a given length with no two adjacent ones, and the counts for length 3 and length 10 were 5 and 144. Those are Fibonacci numbers, and that lesson noted that the counting version is a dynamic programming exercise rather than a search.
Here it is. Counting them without generating them is the whole point: generation is exponential and counting is linear.
This memoizes on the length alone, ignoring the other parameter the answer depends on. Type the two values it prints.
def count_bad(length, last_was_one=False, seen=None): if seen is None: seen = {} if length == 0: return 1 if length in seen: return seen[length] total = count_bad(length - 1, False, seen) if not last_was_one: total += count_bad(length - 1, True, seen) seen[length] = total return total def count_good(length, last_was_one=False, seen=None): if seen is None: seen = {} if length == 0: return 1 key = (length, last_was_one) if key in seen: return seen[key] total = count_good(length - 1, False, seen) if not last_was_one: total += count_good(length - 1, True, seen) seen[key] = total return total print(count_bad(10), count_good(10))One recurrence, three ways. ways_slow counts sequences of 1s and 3s summing to n, by plain recursion. ways_memo does the same with memory. ways_rolling does it with a fixed number of variables. All three must agree.
Tests
print([ways_slow(n) for n in range(7)])print([ways_memo(n) for n in range(7)])print([ways_rolling(n) for n in range(7)])print(ways_memo(30) == ways_rolling(30), ways_rolling(30))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.