Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.

Similar presentations


Presentation on theme: "Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion."— Presentation transcript:

1 Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion

2 © 2006 Pearson Addison-Wesley. All rights reserved11-2 Recursive Problem 1 Calculate the sum of an array of integers

3 © 2006 Pearson Addison-Wesley. All rights reserved11-3 Recursive Problem 2 Reverse the order of the characters in a string

4 © 2006 Pearson Addison-Wesley. All rights reserved11-4 Recursive Problem 3 Count number of digits in an integer

5 © 2006 Pearson Addison-Wesley. All rights reserved11-5 Recursive Problem 4 A palindrome is a phrase that reads the same forwards and backwards. For example: –radar –able was I ere I saw elba –pan a nap Write a program that answers the question, "Is this string a palindrome?"

6 © 2006 Pearson Addison-Wesley. All rights reserved11-6 Recursive Problem 5 print out all the permutations of a string Example: permutations of "abc": abc acb bac bca cab cba (assume no repeated letters in string) Much simpler to solve this with recursion than without.

7 © 2006 Pearson Addison-Wesley. All rights reserved11-7 Permutations Solution –Given the empty set { }, the only possible permutation is { } –Given the set {A}, the only possible permutation is {A} –Given the set {A, B}, the possible permutations are {AB, BA} –Given the set {A, B, C}, the possible permutations are {ABC, ACB, BAC, BCA, CAB, CBA} –Etc.

8 © 2006 Pearson Addison-Wesley. All rights reserved11-8 Finding all permutations of n objects To find all permutations of n objects: –Find all permutations of n-1 of those objects –Insert the remaining object into all possible positions of each permutation of n-1 objects Example: To find all permutations of 3 objects {A, B, C} –Find all permutations of 2 of the objects, say B and C : B C and C B –Insert the remaining object, A, into all possible positions (marked by ^) in each of the permutations of B and C : ^ B ^ C ^ and ^ C ^ B ^ – ABC BAC BCA ACB CAB CBA

9 © 2006 Pearson Addison-Wesley. All rights reserved11-9 Towers of Hanoi In a later course


Download ppt "Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion."

Similar presentations


Ads by Google