Advanced Java Programming
E N D
Presentation Transcript
Advanced Java Programming CSS446 Spring 2014 Nan Wang
Chapter Goals • To learn to “think recursively” • To be able to use recursive helper methods • To understand the relationship between recursion and iteration • To understand when the use of recursion affects the efficiency of an algorithm • To analyze problems that are much easier to solve by recursion than by iteration • To process data with recursive structures using mutual recursion
Recursion • The recursion method is to break up complex computational problem into simpler, smaller ones. • Recursion refers to that face that the same computation recurs, or occurs repeatedly as the problem is solved. • E.g. Fibonacci sequence:
Triangle Numbers • To compute the area of a triangle of width n, assuming that each [] square has area 1. • [] • [][] • [][][] • [][][][] • Area(1) = 1 • Area(4) = Area(3) + 1 • =>Area(n) = Area(n-1) + n
Palindrome test • Test whether a sentence is a palindrome – a string that is equal to itself when you reverse all characters. • Madam, I’m Adam • A man, a plan, a canal – Panama!
Fibonacci Sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Permutations • The string ‘eat’ has six permutations: • eat eta aet ate tea tae • Index=0 e—at ta • Index=1 a—et te • Index=2 t—ea ae
Mutual Recursion • Recursive solution 1: a method call itself to solve a simpler problem. • In a mutual recursion, a set of cooperating methods calls each other repeatedly.
Evaluating an Expression • Compute the values of arithmetic expressions • 3+4*5, (3+4)/5, 3-(4-5) etc
Backtracking • Backtracking is a problem solving technique that builds up partial solutions that get increasingly closer to the goal. • If a partial solution cannot be completed, one abandons it and returns to examining the other candidates.
Homework assignment 5 • DO NOT implement • Submit a softcopy to usm.java@gmail.com