1 / 12

Class 4 - Recursion

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.

Télécharger la présentation

Class 4 - Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Class 4 - Recursion • More examples of recursion • Methods with multiple arguments

  2. 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.

  3. Example Given n, print numbers 0, ..., n-1, n.

  4. Example Given n, calculate n!, defined to be the nth number in the list 1, 1, 2, 6, 24, 120, … (counting from zero)

  5. Example Given n >=0, print n asterisks. > java stars Input number: 4 ****

  6. Example Given n>=0, print a triangle out of asterisks. > java triangle Input number: 4 **** *** ** *

  7. Example Given integers m, n >= 0, compute mn

  8. 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

  9. 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.

  10. 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:

  11. 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.

  12. 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

More Related