Lecture05_Recursion
Lecture05_Recursion
Algorithms
"
Recursion!
The Recursion Pattern"
• Recursion: when a method calls itself!
• Classic example--the factorial function:!
– n! = 1· 2· 3· ··· · (n-1)· n!
• Recursive definition:!
⎧ 1 if n = 0
f (n) = ⎨
⎩n ⋅ f (n − 1) else
• As a Java method:!
// recursive factorial function
public static int recursiveFactorial(int n) {
if (n == 0) return 1;
// base case
else return n * recursiveFactorial(n- 1); //
recursive case
}!
recursiveFactorial(4)
recursive call! call return 3*2 = 6
drawTicks (2 )
central tick length L >1 drawTicks (1 )
is composed of the drawTicks ( 0 )
following:! drawOneTick (1 )
drawOneTick (2 )
tick length L-1,!
drawTicks (1 )
– a single tick of length L,!
drawTicks (0 )
– an interval with a central drawOneTick (1 )
tick length L-1.! drawTicks (0 )
drawOneTick (3 )
drawTicks (2 )
(previous pattern repeats )
⎧ 1 if n = 0
f (n) = ⎨
⎩n ⋅ f (n − 1) else
• As a Java method:!
// recursive factorial function
public static int recursiveFactorial(int n) {
if (n == 0) return 1;
// base case
else return n * recursiveFactorial(n- 1);
// recursive case
}!
Phạm Bảo Sơn - DSA
Linear Recursion"
• Test for base cases. !
– Begin by testing for a set of base cases (there should be at
least one). !
– Every possible chain of recursive calls must eventually reach
a base case, and the handling of each base case should not
use recursion.!
• Recur once. !
– Perform a single recursive call. (This recursive step may
involve a test that decides which of several possible recursive
calls to make, but it should ultimately choose to make just
one of these calls each time we perform this step.)!
– Define each possible recursive call so that it makes progress
towards a base case.!
• Example trace:"
0, 8
0, 4 4, 4
0, 2 2, 2 4, 2 6, 2
0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1
!
Algorithm for Multiple
Recursion"
Algorithm PuzzleSolve(k,S,U):!
Input: An integer k, sequence S, and set U (the universe of elements to test)!
Output: An enumeration of all k-length extensions to S using elements in U!
!without repetitions!
if k = 0 then"
!Test whether S is a configuration that solves the puzzle!
"if S solves the puzzle then"
" "return “Solution found: ” S!
else !
for all e in U do"
! !Remove e from U !{e is now being used}!
! !Add e to the end of S!
" "PuzzleSolve(k - 1, S,U)!
! !Add e back to U !{e is now unused}!
! !Remove e from the end of S!
!
Initial call
PuzzleSolve( 3,(),{a,b,c})