Factorial � private int factorial (int n) { � � assert n >= 0; � � � � if (n == 0) { � � � return 1; � � } � � � � return n * factorial(n-1); � } factorial(3) => 3 * factorial(2) = 6 2 � factorial(2) => 2 * factorial(1) 1 = 2 1 factorial(1) => 1 * factorial(0) = 1 factorial(0) => 1 1 Recursive Thinking Define the solution to a problem in terms of a solution to one or more “smaller” subproblems Define a base case, a subproblem that can be solved directly. 2 Tuesday, April 27, 2010
Factorial � private int factorial (int n) { � � assert n >= 0; � � � � if (n == 0) { Base case � � � return 1; � � } � � � � return n * factorial(n-1); Smaller � } subproblem � Solution to recursive case 3 Recursion Humor http:/ /imgs.xkcd.com/comics/ not_enough_work.png 4 Tuesday, April 27, 2010
More Recursion Humor http:/ / www.thinkgeek.com/ images/products/zoom/ b2ae_recursion.jpg 5 Recursive Structures Define a data structure as a piece of data followed by a smaller data structure of the same type Define a base case, a trivial piece of data with nothing following it. 6 Tuesday, April 27, 2010
Drawing with the Mouse 7 Drawing with the Mouse Lots of short lines! Call one group of connected lines a “scribble” 8 Tuesday, April 27, 2010
What is a Scribble? A line segment, followed by A shorter Scribble Base case: an “empty” scribble 9 Scribble Hierarchy <<interface>> Scribble Recursive Empty Scribble Scribble 10 Tuesday, April 27, 2010
RecursiveScribble public class RecursiveScribble implements Scribble { / / This line private Line2D line; private Color color; / / The lines that follow it private Scribble rest; / / Methods ... } 11 EmptyScribble public class EmptyScribble implements Scribble { / / No instance variables!! / / Methods ... } 12 Tuesday, April 27, 2010
Changing the Color of a Scribble in RecursiveScribble: public void setColor (Color newColor) { / / Change the color of this line color = newColor; / / Recursively change the rest of the scribble rest.setColor (newColor); } in EmptyScribble: public void setColor (Color newColor) { / / Nothing to do! } 13 Broccoli 14 Tuesday, April 27, 2010
Broccoli Base case => Flower Smaller substructure => 3 More pieces of broccoli Little data => Stem 15 Towers of Hanoi End of the world in 585 billion years! http:/ / en.wikipedia.org/wiki/Tower_of_Hanoi 16 Tuesday, April 27, 2010
Recommend
More recommend