chapter_10
chapter_10
1. Arguments n=3
2. Local variables
3. Place holder for the value A: sum(n-1) = ?
returned by a called function
4. A return value return ?
Box trace of sum(3)
cout << sum(3);
n=3 n=2 n=1
A: sum(n-1)=? A: sum(n-1)=?
return ? return ? return 1
n=3
A: fact(n-1) = ?
return ?
CSS342: Recursion 6
Box trace of fact(3)
cout << fact(3);
n=3 n=2 n=1
A: fact(n-1)=? A: fact(n-1)=?
return ? return ? return 1
n n-1 n-1
= + , 1 < k < n (recursive solution)
k k k-1
n n!
= , 1 < k < n (closed-form solution)
k k!(n-k)!
with base cases:
n n
= n (k = 1), = 1 (k = n)
1 n
n choose k (combinations)
int Combinations(int n, int k)
{
if(k == 1) // base case 1
return n;
else if (n == k) // base case 2
return 1;
else
return(Combinations(n-1, k) + Combinations(n-1, k-1));
}
Tower of Hanoi
• Pole A with heavy metal disks of various
sizes stacked on top of each other.
• Objective: Transfer disks from Pole A to
Pole B.
• Constraint: Disks are so heavy that stacking
to be done with largest at the bottom and in
order.
• Support: You may use a spare pole during
transfer.
Towers of Hanoi
A B C
4
move(2, A, C, B) move(1, A, B, C) move(2, C, B, A)
Locally, A is A, C is B, B is C. Locally C is A, B is B, A is C.
1
move(1, A, B, C) 5 move(1, C, A, B)
2 6
move(1, A, C, B) move(1, C, B, A)
3 7
move(1, B, C, A) move(1, A, B, C)
Recursion vs. iteration
• Iteration can be used in place of recursion
– An iterative algorithm uses a looping construct
– A recursive algorithm uses a branching structure
• Recursive solutions are often less efficient, in
terms of both time and space, than iterative
solutions
• Recursion can simplify the solution of a problem,
often resulting in shorter, more easily understood
source code