Recursion

Induction Review

If you are comfortable with mathematical induction, then you will like recursion. In mathematical induction, you can prove a statement is true as follows:

  1. Show the statement is true for a base case, e.g. for n=1, where n is some measure of the size of the problem.

  2. Assume statement is true for some size n-1.

  3. Prove statement is true for n based on the assumption that statement is true for n-1.

Example

Show that you can always tile a 2n by 2n chessboard with one missing square, using L shaped pieces:

Base case: n=1. With one tile you have created a 2 by 2 chessboard with one missing tile.

Just to be sure, let's try it for n=2:

Now, assume it can be done for n-1, show it works for n.

Recursion

A recursive method is a method that makes a call to itself. For example, what does the following do?

public class Recurse
{
   public static void main(String args[])
   {
      recurse(10);
   }

   public static void recurse(int n)
   {
      if (n<0) return;
      else {
        recurse(n-1);
        System.out.println(n);
      }
   }
}

The idea is as follows. Suppose you want to solve a problem of a given size n (e.g sort 10 numbers, print 20 numbers, compute 12!). There are 2 things I must ask myself:

If my answer to both the above questions is yes, then I can solve my problem using recursion.


doProblem(int size)
   if size is small, return the answer
   otherwise
       Assume you can use doProblem(size-1) to solve problem for (size-1)
       Use result for (size-1) to solve the problem for size. 
       Return the result for size.

The above program does this for printing numbers from 0 to n. If n<0 then it doesn't do anything. Otherwise, it calls recurse to print the numbers from 0 to n-1, and then it prints out n.

How would you compute the factorial of a number recursively?

Solving the Towers of Hanoi

Turtle Graphics: Koch diagram, twigs

Most any loop can be replaced with a recursive method.


next lecture