11 - 03 Feb - From Recursion to Dynamic Programming

Post on 14-Apr-2017

110 views 2 download

Transcript of 11 - 03 Feb - From Recursion to Dynamic Programming

CS 321. Algorithm Analysis & Design Lecture 11

Recursion - Continued.Fibonacci Numbers

(In class we started with a recap of Independent Set, see the previous set of slides.)

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

How many ways to tile a corridor of length n?

What’s the last tile?

Black Red

Black

C(4) = C(3) + C(2)

C(n) = C(n-1) + C(n-2)

C(1) = 1, C(2) = 2, C(3) = 3

The general recurrence.

Notice that there is redundancy in the recursion tree for computing C(n).

C(n)

C(n-1) C(n-2)

C(n-3)C(n-2) C(n-4)C(n-3)

[If implemented directly]

Memoization - The Basic Idea

Simply store the values when you compute them.

Memoization - The Basic Idea

Simply store the values when you compute them.

Before delving into a recursive rabbit hole, check if the value is already stored somewhere.

Memoization - The Basic Idea

Simply store the values when you compute them.

Before delving into a recursive rabbit hole, check if the value is already stored somewhere.

Get into recursion on a need-to basis.

Memoization - The Basic Idea

Simply store the values when you compute them.

Before delving into a recursive rabbit hole, check if the value is already stored somewhere.

Get into recursion on a need-to basis.

We’re doing “actual work” for only n distinct subproblems. The rest is only table lookups.

Memoization - The Basic Idea