120 likes | 247 Views
Class 4 - Recursion. More examples of recursion Methods with multiple arguments. Thinking recursively. Key ideas: Know exactly what the method is supposed to do. Assume method works for smaller values. Then just figure out how to use it to compute method for larger values.
E N D
Class 4 - Recursion • More examples of recursion • Methods with multiple arguments
Thinking recursively Key ideas: • Know exactly what the method is supposed to do. • Assume method works for smaller values. Then just figure out how to use it to compute method for larger values. • Don’t forget base cases - small values that can be calculated directly.
Example Given n, print numbers 0, ..., n-1, n.
Example Given n, calculate n!, defined to be the nth number in the list 1, 1, 2, 6, 24, 120, … (counting from zero)
Example Given n >=0, print n asterisks. > java stars Input number: 4 ****
Example Given n>=0, print a triangle out of asterisks. > java triangle Input number: 4 **** *** ** *
Example Given integers m, n >= 0, compute mn
Example Given integers m, n >= 0, compute mn more quickly, using this idea: mn = 1, if n=0 (mn/2)2, if n even mmn-1, if n odd
Why more efficient? Count multiplications: • pow(m,n): n-1 multiplications • fastpow(m,n): log2n multiplications One advantage of recursion is that it sometimes suggests much more efficient algorithms.
m n ( ) Binomial coefficients (“m choose n”) = number of ways of selecting n items from m>=n objects (disregarding order). E.g. 4 2 ( ) = 6:
m’ n’ m n ( ( ) ) Binomial coefficients (cont.) Assume we can calculate for m’ <= m and/or n’ <= n. How does this help us calculate ? Select element e out of the m elements. To choose the n elements, either: • Include e: choose n-1 out of remaining m-1 objects; or • Exclude e: choose n out of remaining m-1 objects.
m n m-1 n-1 m 0 0 n m-1 n ( ( ( ( ( ) ) ) ) ) Binomial coefficients (cont.) Thus, binomial coefficient can be calculated recursively: = + Base cases: = 1 = 0