Title: Top Down Problem Solving
1Recursion
2Top Down Problem Solving
Many problems become much more manageable to
solve when they have been broken down into
smaller problems. This technique has a few
names top down problem solving divide and
conquer The problem is divided using stepwise
refinement. For certain problems, each stepwise
refinement is actually an instance of the bigger
problem using a smaller input set. These
problems have a recursive solution.
3Recursion
Any function that is implemented by calling
itself is called a recursive function. Consider
the following crude implementation of factorial
int factorial(int value) int ret 1
if (value gt 1) ret value
factorial(value -1) return ret
4When to Use Recursion
- Problems having the following characteristics
lend themselves to recursion - One or more simple cases of the problem have a
straightforward, non-recursive solution called
the base case. - The other cases can be redefined in terms of
problems that are closer to the simple cases - By applying the redefinition process every time
the recursive function is called, eventually the
problem is reduced to the base case - if this is the simple case
- solve it
- else
- redefine the problem using recursion
5Classic Recursive Solutions
Some classic recursive problems
include Factorial Fibonacci Reverse
string Counting characters in a string Binary
search Sorting algorithms Towers of Hanoi
6Towers of Hanoi Algorithm
Inputs n the number of disks to be moved from
peg the peg where disks are being moved from to
peg - the peg where disks are being moved to aux
peg the auxiliary peg needed for other
moves Steps If n is 1 Then move disk 1 from
the from peg to the to peg Else move n-1
disks from the from peg to the aux peg using the
to peg move disk n from the from peg to the to
peg move n-1 disks from the aux peg to the to
peg using the from peg The number of steps
required is 2n 1.
7Performance of Recursion
Recursive solutions often look quite simple and
elegant, but there is an associated
cost. Recursive functions typically make a
significant number of function calls. Recall how
function calls are implemented. They require the
use of a stack to store the calling state and to
push on data associated with the recursive
function call. This can be pretty intensive on
your stack. Recursive functions that do not have
the correct base case often cause stack
overflow! Generally, it is recommended to choose
an iterative solution over a recursive solution.