Recursion

13.3 - 13.4

Fibonacci Sequence

The Efficiency of Recursion

Call Tree for Computing fib(6)

The Efficiency of Recursion

The Efficiency of Recursion

Iterative isPalindrome Method

public boolean isPalindrome() 
{ 
   int start = 0; 
   int end = text.length() - 1; 
   while (start < end) 
   { 
      char first = Character.toLowerCase(text.charAt(start)); 
      char last = Character.toLowerCase(text.charAt(end); 
      if (Character.isLetter(first) && Character.isLetter(last)) 
      { 
         // Both are letters. 
         if (first == last) 
         { 
            start++; 
            end--; 
         } 
         else 
         { 
            return false; 
         } 
      } 
      if (!Character.isLetter(last)) { end--; } 
      if (!Character.isLetter(first)) { start++; } 
   } 
   return true; 
}

Lecture 8 Clicker Question 1

Consider the triangle number computation in the Triangle.getArea method.

Permutations

To Generate All Permutations

You will define a class with a recursive method. Here is the start of the class

public class PermutationGenerator
{
   private String word;

   /**
      Constructs a permutation generator.
      @param aWord the word to permute
   */
   public PermutationGenerator(String aWord)
   {
      word = aWord;
   }
   

For the recursive method

You will need an array list to hold all the permutations

   public ArrayList getPermutations()
   {
      ArrayList permutations = new ArrayList();
      

Base case

      // The empty string has a single permutation: itself
      if (word.length() == 0) 
      { 
         permutations.add(word); 
         return permutations; 
      }

To Generate All Permutations

To Generate All Permutations

To Generate All Permutations

Lecture 8 Clicker Question 2

What are all permutations of the four-letter word beat?

  1. beat, eatb, atbe, tbea
  2. beat, beta, baet, bate, btea, btae
  3. beat, beta, baet, bate, btea, btae, eatb, etab, aetb, ateb, teab, taeb
  4. b followed by the six permutations of eat, e followed by the six permutations of bat, a followed by the six permutations of bet, and t followed by the six permutations of bea