Download Assignment 1 for Object Oriented Programming II | CMSC 132 and more Study notes Computer Science in PDF only on Docsity! Recursion CMSC 132 Department of Computer Science University of Maryland, College Park Overview Recursion Base Case/Recursive Step Recursion vs. Iteration Examples Base Case/Recursive Step Base case – solution to small problem Recursive step Simplifies original problem Recursively applies current algorithm to sub- problem Combine results if necessary A recursive method is a method that “calls itself” Alternative definition: A recursive method is a method that calls a method that performs the same task the current method performs Recursion vs. Iteration Any problem you can solve recursively can be solved without recursion Iteration over a list/sequence is very similar to using recursion to combine the result from the first element with the result from the rest of the list Counting vowels with recursion int countVowels(String s) { if (s.length() == 0) return 0; int tailResult = countVowels(s.substring(1)); switch (s.charAt(0)) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: return tailResult+1; default: return tailResult; } } Recursion vs. Iteration Counting vowels with iteration int countVowels(String s) { int result = 0; for(int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: result++; break; } return result; } Recursive Permutation Generation Define a function calculatePermutations(int [] a) that generates each permutation of a and calls handlePermutation(int [] a) with each generated permutation Hint: define a recursive helper function calculatePermutations(int [] a, int k) that permutes the values in a[k ... a.length-1] See PrintPermutations.java in code distribution Not Exciting Recursion Using recursion where iteration would work just as well isn’t that exciting Sometimes, a little to think about it as a recursive problem In Java, it isn’t particularly efficient for long lists or deep recursion In some languages (such as Scheme) that support tail recursion, it is as efficient as iteration. In fact, it can be the only/preferred way to implement iteration has to be a special kind of recursion, called tail recursion Interesting recursion Binary search Quicksort Mergesort nQueens Place queens on a board such that every row and column contains one queen, but no queen can attack another queen place queens on nxn board recursive approach: assume you’ve already placed k queens