50 likes | 483 Views
Recursion. Brian Toone 10/14/09. Recursion. When a method calls itself Example int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }. Properties of recursion. All recursion must end Base case The condition which terminates the recursion
E N D
Recursion Brian Toone 10/14/09
Recursion • When a method calls itself • Example int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }
Properties of recursion • All recursion must end • Base case • The condition which terminates the recursion • Each recursive call should make progress towards base case • Factorial – the base case occurs when n <= 1 int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }
Example • Display all possible orderings of the letters in the word “carbon” • Recursive solution • Concatenate ‘c’ to the beginning of each ordering returned from a recursive call made on “arbon” • Concatenate ‘a’ to the beginning of each ordering returned from a recursive call made on “crbon” • The recursive call is made to obtain the orderings of the subwords “arbon”, “crbon”, “cabon”, “caron” • Base case: only one letter - simply return it