# Understanding Recursion

• Step 1: nuts and bolts

Understanding how a function can invoke itself

• Step 2: coding

Writing recursive functions to implement existing recursive relationships (e.g., subtrees are trees).

• Step 3: problem solving

Applying problem solving strategies (divide and conquer, dynamic programming) to find recursive relationships.

# Puzzle: Pirates & Gold

• 7 pirates and 65 gold pieces to be distributed.

• Pirates are greedy, rational and well-ordered.

• Captain distributes all the gold.

• If more than half the pirates are unhappy, they will mutiny, kill the current captain, and promote the next pirate in the well-ordering to be the new captain.

• If you are the original captain, how should you distribute the gold so you keep the most possible and do not incite a mutiny?

# Quick Review of Nuts & Bolts

• A function can call itself just like any other function.

• Each "copy" of the function has its own local variables.

• Make recursion work:

• must have a least one base case and one recursive case.

• test for base case must execute before any recursive case.

• recursive calls must make "progress" towards base case.

• recursive calls must not skip over base case.

# Example: Fibonacci Numbers

int fib(int n) { if (n <= 1) return 1; // base case return fib(n-1) + fib(n-2) ; // two recursive calls! }

• My least favorite example of recursion.

• Turns a O(n) time program into a O(2n) time program.

• Convinces people not to use recursion.

# Euclid's GCD Algorithm

int gcd(int m, int n) { int r = m % n ; if (r == 0) return n ; return gcd(n,r) ; }

• Computes the greatest common divisor of m and n.

• Much faster than checking all numbers between 2 and n.

• Recursive relation not immediately obvious.

• Factoid: slowest when m and n are consecutive Fibonacci numbers.

# Memoization

Note: "memoization" (no r) not "memorization"

• Recursive Fibonacci number function is slow because it recomputes the value of fib(i) many times.

• We should store the answer to fib(i) in a table.

• Check if the memoization table already holds the correct answer before computing fib(i).

• Turns a O(2n) time program into a O(n) time program.

# Coin Changing Problem

• Use the smallest number of coins to make change for n cents.

• For U.S. currency: use largest denomination first.

• Greedy fails for "weird" coin systems:

Make change for 14 cents using 6-cent, 4-cent and 1-cent coins.

Greedy: 2 6-cent coins, 2 1-cent coins

Optimum: 1 6-cent coins, 2 4-cent coins

• How do we solve this problem recursively?