Recursion Lecture Notes: Recursion Weiss Ch. 7, Pp. 231-243, 244-267, 272-282
Recursion Lecture Notes: Recursion Weiss Ch. 7, Pp. 231-243, 244-267, 272-282
Lecture Notes
Recursion
2
Recursive definitions
Consider the following list of numbers:
24 -> 88 -> 40 -> 37 /
5
Factorial example
The factorial for any positive integer N, written
N!, is defined to be the product of all integers
between 1 and N inclusive
n! n (n 1) (n 2) ...1
public static int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++)
product *= i;
return product;
}
6
Recursive factorial
factorial can also be defined recursively:
n 1 n f (n 1)
f ( n)
n 0 1
A factorial is defined in terms of another
factorial until the basic case of 0! is reached
public static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
} 7
Recursive programming
A method in Java can call itself; if written that
way, it is called a recursive method
A recursive method solves some problem.
The code of a recursive method should be
written to handle the problem in one of two
ways:
Base case: a simple case of the problem that can
be answered directly; does not use recursion.
Recursive case: a more complicated case of the
problem, that isn't easy to answer directly, but can
be expressed elegantly with recursion; makes a
recursive call to help compute the overall answer
8
Recursive power example
Write method pow that takes integers x and y
as parameters and returns xy.
xy = x * x * x * ... * x (y times, in total)
An iterative solution:
pow(x, 0) = 1
pow(x, y) = x * pow(x, y-1), y > 0
pow(4, 3) = 4 * pow(4, 2)
= 4 * 4 * pow(4, 1)
= 4 * 4 * 4 * pow(4, 0)
= 4 * 4 * 4 * 4 * pow(4, -1)
= 4 * 4 * 4 * 4 * 4 * pow(4, -2)
= ... crashes: Stack Overflow Error!
12
Activation records
activation record: memory that Java
allocates to store information about each
running method
return point ("RP"), argument values, local variable
values
Java stacks up the records as methods are called; a
method's activation record exists until it returns
drawing the act. records helps us trace the behavior
of a recursive method
_
| x = [ 4 ] y = [ 0 ] | pow(4, 0)
| RP = [pow(4,1)] |
| x = [ 4 ] y = [ 1 ] | pow(4, 1)
| RP = [pow(4,2)] |
| x = [ 4 ] y = [ 2 ] | pow(4, 2)
| RP = [pow(4,3)] |
| x = [ 4 ] y = [ 3 ] | pow(4, 3)
| RP = [main] |
| | main
13
Tracing recursive methods
Consider the following method:
public static int mystery1(int x, int y) {
if (x < y)
return x;
else
return mystery1(x - y, y);
}
For each call below, indicate what value is returned:
mystery1(6, 13) ____________
mystery1(14, 10) ____________
mystery1(37, 10) ____________
mystery1(8, 2) ____________
mystery1(50, 7) ____________
14
Tracing recursive methods
public static void mystery2(int n) {
if (n <= 1)
System.out.print(n);
else {
mystery2(n/2);
System.out.print(", " + n);
}
}
For each call below, indicate what output is printed:
mystery2(1) ____________
mystery2(2) ____________
mystery2(3) ____________
mystery2(4) ____________
mystery2(16) ____________
mystery2(30) ____________
mystery2(100) ____________ 15
Tracing recursive methods
public static int mystery3(int n) {
if (n < 0)
return -mystery3(-n);
else if (n < 10)
return n;
else
return mystery3(n/10 + n % 10);
}
For each call below, indicate what value is returned:
mystery3(6) ____________
mystery3(17) ____________
mystery3(259) ____________
mystery3(977) ____________
mystery3(-479) ____________
16
Tracing recursive methods
public static void mystery4(String s) {
if (s.length() > 0) {
System.out.print(s.charAt(0));
if (s.length() % 2 == 0)
mystery4(s.substring(0, s.length() - 1));
else
mystery4(s.substring(1, s.length()));
System.out.print(s.charAt(s.length() - 1));
}
}
19
Recursive string problems
Problem: Write a recursive method
isPalindrome that takes a string and returns
whether the string is the same forwards as
backwards.
(Hint: examine the end letters.)
i = 16
0 4 min
1 7
2 16
3 20 mid (too big!)
4 37
5 38
6 43 max
23
Binary search example, cont'd
i = 16
0 4 min
1 7 mid (too small!)
2 16 max
3 20
4 37
5 38
6 43
24
Binary search example, cont'd
i = 16
0 4
1 7
2 16 min, mid, max (found it!)
3 20
4 37
5 38
6 43
25
Binary search pseudocode
binary search array a for value i:
if all elements have been searched,
result is -1.
examine middle element a[mid].
if a[mid] equals i,
result is mid.
if a[mid] is greater than i,
binary search left half of a for i.
if a[mid] is less than i,
binary search right half of a for i.
26
Runtime of binary search
How do we analyze the runtime of binary search?
T(n) = T(n/2) + c
T(1) = c
O(n ), k
ab k
T(n) = T(n/2) + c
T(1) = c
1 = 20, therefore:
T(n) = O(n0 log n) = O(log n)
(recurrences not needed for our exams) 31
Recursive backtracking
backtracking: an elegant technique of
searching for a solution to a problem by
exploring each possible solution to completion,
then "backing out" if it is unsatisfactory
often implemented using recursion
can yield straightforward solutions for otherwise
extremely difficult problems
a "depth-first" algorithmic technique (tries each
possible solution as deeply as possible before giving
up)
32
Backtracking: escape a maze
Consider the problem of escaping a maze, from
start at 's' to exiting the edge of the board.
XXXXXXXXXXXXX XXXXXXXXXXXXX
X X XX X X X..XX X
X X X XXX X ..X X.X XXX X
X X X X X sX X.X X.X X...X
X X X X X --> X.X X.....X X
X X X X X X X X.X X.X X X X
X X X X X X.....X X X X
XXXXXXXXXXXXX XXXXXXXXXXXXX
33
Backtracking: escape a maze
Maze escaping algorithm, cases of interest:
if I am on an open square on the edge of the
board, ...
38
Dynamic programming
dynamic programming: saving results of
subproblems so that they do not need to be
recomputed, and can be used in solving other
subproblems
example: saving results from sub-calls in a list or
table
can dramatically speed up the number of calls for a
recursive function with overlapping subproblems
what is the change in Big-Oh for fibonacciR?
(non-trivial to calculate exactly)
39
Dynamic fibonacci pseudocode
table[] {table[0] = 1, table[2] = 1}
max = 2
fibonacciR(n):
n is in table, return table[n]
else
compute fibonacciR(n-1) and fibonacciR(n-2)
add them to get table[n] = fibonacciR(n)
set max = n