Post - 2030 L3 Current-Recursion
Post - 2030 L3 Current-Recursion
EECS 2030
Lecture 3 :: Recursion
Think recursively
1
2020-09-18
Think
recursively
2
2020-09-18
Recursion
• Recursion is the process of defining a problem (or the solution to a
problem) in terms of (a simpler version of) itself.
▪ number of characters in a string is 1 + number characters in the
remaining string
o lengh("ABCD") = 1 + length("BCD")
▪ a × b can be solved by a + a × (b-1)
▪ ab can be solved by a × ab-1
▪ sum of n numbers is sum of first and rest
o sum(4,8,7,5) = 4 + sum(8,7,5)
▪ Max value in a list is the larger of first and max of rest list
▪ Factorial n can be defined/solved as n! = n * (n-1)!
▪ Fibonacci sequence is defined as: F(i) = F(i-1) + F(i-2)
5
Why recursion?
• Solves some problems more naturally than
iteration
▪ In computer science, some problems are more easily
solved by using recursive functions.
o Tower of Hanoi
3
2020-09-18
Recursive Definitions
• Every recursive algorithm involves at least 2 cases:
▪ Base case(s).
▪ Recursive calls/cases.
• General case:
▪ Case in recursive definition in which a smaller version of itself
is called
▪ Usually by changing the parameter(s).
▪ Must eventually be reduced to a base case
o Progress toward base case
4
2020-09-18
Recursion
“To get into my house
I must get the key from a smaller house
length(“ABCD”)
= 1 + length(“BCD”)
= 1 + ( 1 + length(“CD”))
= 1 + ( 1 + ( 1 + length(“D”))) Can save restL
=101 + ( 1 + ( 1 + (1+ (1+length(“”) )))
=1+ (1+ ( 1 + (1+ (1+0) ))) = 4
10
5
2020-09-18
Recursion
“To get into my house
I must get the key from a smaller house
length(“ABCD”)
= 1 + length(“BCD”)
= 1 + ( 1 + length(“CD”))
= 1 + ( 1 + ( 1 + length(“D”)))
= 1 + ( 1 + ( 1 + (1+ length(“”) )))
=11 1 + ( 1 + ( 1 + (1+ 0 ))) = 4
11
Recursion
“To get into my house
I must get the key from a smaller house
length(“ABCD”)
= 1 + length(“BCD”)
= 1 + ( 1 + length(“CD”))
= 1 + ( 1 + ( 1 + length(“D”)))
= 1 + ( 1 + ( 1 + (1+ length(“”) )))
=12 1 + ( 1 + ( 1 + (1+ 0 ))) = 4
12
6
2020-09-18
Recursive Methods
• Caller “pause” on method call
13
2
int a = length("ABCD") static int length ("CD")
{
System.out.println(a); if ("CD".equals("")
return 0;
return 1 + length("CD".substring(1));
}
14
14