23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Code Fragment 3.36: Comput<strong>in</strong>g the kth Fibonacci<br />

number us<strong>in</strong>g l<strong>in</strong>ear recursion.<br />

The algorithm given <strong>in</strong> Code Fragment 3.36 shows that us<strong>in</strong>g l<strong>in</strong>ear recursion to<br />

compute Fibonacci numbers is much more efficient than us<strong>in</strong>g b<strong>in</strong>ary recursion.<br />

S<strong>in</strong>ce each recursive call to L<strong>in</strong>earFibonacci decreases the argument k by 1,<br />

the orig<strong>in</strong>al call L<strong>in</strong>earFibonacci(k) results <strong>in</strong> a series of k − 1 additional<br />

calls. That is, comput<strong>in</strong>g the kth Fibonacci number via l<strong>in</strong>ear recursion requires k<br />

method calls. This performance is significantly faster than the exponential time<br />

needed by the algorithm based on b<strong>in</strong>ary recursion, which was given <strong>in</strong> Code<br />

Fragment 3.35. Therefore, when us<strong>in</strong>g b<strong>in</strong>ary recursion, we should first try to<br />

fully partition the problem <strong>in</strong> two (as we did for summ<strong>in</strong>g the elements of an<br />

array) or, we should be sure that overlapp<strong>in</strong>g recursive calls are really necessary.<br />

Usually, we can elim<strong>in</strong>ate overlapp<strong>in</strong>g recursive calls by us<strong>in</strong>g more memory to<br />

keep track of previous values. In fact, this approach is a central part of a technique<br />

called dynamic programm<strong>in</strong>g, which is related to recursion <strong>and</strong> is discussed <strong>in</strong><br />

Section 12.5.2.<br />

3.5.3 Multiple Recursion<br />

Generaliz<strong>in</strong>g from b<strong>in</strong>ary recursion, we use multiple recursion when a method may<br />

make multiple recursive calls, with that number potentially be<strong>in</strong>g more than two.<br />

One of the most common applications of this type of recursion is used when we<br />

wish to enumerate various configurations <strong>in</strong> order to solve a comb<strong>in</strong>atorial puzzle.<br />

For example, the follow<strong>in</strong>g are all <strong>in</strong>stances of summation puzzles:<br />

pot + pan = bib<br />

dog + cat = pig<br />

boy + girl = baby<br />

202

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!