DS Lecture 10 - Recursion (Fibonocci, Factorial)
DS Lecture 10 - Recursion (Fibonocci, Factorial)
Lecture # 10
Recursion
(Fibonocci Sequence, Factorial)
Recursion
Sometimes, the best way to solve a problem is by solving a
smaller version of the exact same problem first.
Recursion is a technique that solves a problem by solving a smaller problem of the same type.
var fib(var n)
var f[n+1]
f[1] = f[2] = 1
for (var i = 3; i <= n; i++)
f[i] = f[i-1] + f[i-2]
return f[n]
Factorial; A classical Example of recursion
Pseudo-code (recursive)
END factorial
Factorial; A classical Example of recursion
Pseudo-code (iterative)
FUNCTION factorial is:
INPUT: integer n such that n >= 0
OUTPUT: [n × (n-1) × (n-2) × … × 1]