27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 8 | Recursion<br />

8.7 Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) <strong>and</strong><br />

pennies (1 cent), write code to calculate <strong>the</strong> number of ways of representing n cents.<br />

SOLUTION<br />

pg 64<br />

This is a recursive problem, so let’s figure out how to do makeChange(n) using prior solutions<br />

(i.e., sub-problems). Let’s say n = 100, so we want to compute <strong>the</strong> number of ways of making<br />

change of 100 cents. What’s <strong>the</strong> relationship to its sub-problems?<br />

We know that makeChange(100):<br />

= makeChange(100 using 0 quarters) + makeChange(100 using 1 quarter) + makeChange(100<br />

using 2 quarter) + makeChange(100 using 3 quarter) + makeChange(100 using 4 quarter)<br />

Can we reduce this fur<strong>the</strong>r? Yes!<br />

= makeChange(100 using 0 quarters) + makeChange(75 using 0 quarter) + makeChange(50<br />

using 0 quarters) + makeChange(25 using 0 quarters) + 1<br />

Now what? We’ve used up all our quarters, so now we can start applying our next biggest<br />

denomination: dimes.<br />

This leads to a recursive algorithm that looks like this:<br />

1 public static int makeChange(int n, int denom) {<br />

2 int next_denom = 0;<br />

3 switch (denom) {<br />

4 case 25:<br />

5 next_denom = 10;<br />

6 break;<br />

7 case 10:<br />

8 next_denom = 5;<br />

9 break;<br />

10 case 5:<br />

11 next_denom = 1;<br />

12 break;<br />

13 case 1:<br />

14 return 1;<br />

15 }<br />

16 int ways = 0;<br />

17 for (int i = 0; i * denom

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

Saved successfully!

Ooh no, something went wrong!