120 likes | 263 Vues
This guide explores recursion with various examples and methods that involve multiple arguments. It emphasizes the key ideas of recursion, including understanding the method's intentions, assuming it works for smaller values, and remembering base cases for direct calculations. With practical examples, you will learn how to print numbers, calculate factorials, and print triangles or stars. We'll also discuss how recursion can lead to more efficient algorithms, particularly through methods such as calculating binomial coefficients and utilizing quick exponentiation techniques.
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