25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Solutions to Chapter 8 | Recursion<br />

8 5 Implement an algorithm to print all valid (e g , properly opened and closed) combinations<br />

of n-pairs of paren<strong>the</strong>ses<br />

EXAMPLE:<br />

SOLUTION<br />

input: 3 (e g , 3 pairs of paren<strong>the</strong>ses)<br />

output: ()()(), ()(()), (())(), ((()))<br />

CareerCup com<br />

pg 64<br />

We can solve this problem recursively by recursing through <strong>the</strong> string On each iteration, we<br />

have <strong>the</strong> index for a particular character in <strong>the</strong> string We need to select ei<strong>the</strong>r a left or a right<br />

paren When can we use left, and when can we use a right paren?<br />

» Left: As long as we haven’t used up all <strong>the</strong> left paren<strong>the</strong>ses, we can always insert a left<br />

paren<br />

» Right: We can insert a right paren as long as it won’t lead to a syntax error When will we<br />

get a syntax error? We will get a syntax error if <strong>the</strong>re are more right paren<strong>the</strong>ses than<br />

left<br />

So, we simply keep track of <strong>the</strong> number of left and right paren<strong>the</strong>ses allowed If <strong>the</strong>re are<br />

left parens remaining, we’ll insert a left paren and recurse If <strong>the</strong>re are more right parens<br />

remaining than left (eg, if <strong>the</strong>re are more left parens used), <strong>the</strong>n we’ll insert a right paren and<br />

recurse<br />

1 public static void printPar(int l, int r, char[] str, int count) {<br />

2 if (l < 0 || r < l) return; // invalid state<br />

3 if (l == 0 && r == 0) {<br />

4 System.out.println(str); // found one, so print it<br />

5 } else {<br />

6 if (l > 0) { // try a left paren, if <strong>the</strong>re are some available<br />

7 str[count] = ‘(‘;<br />

8 printPar(l - 1, r, str, count + 1);<br />

9 }<br />

10 if (r > l) { // try a right paren, if <strong>the</strong>re’s a matching left<br />

11 str[count] = ‘)’;<br />

12 printPar(l, r - 1, str, count + 1);<br />

13 }<br />

14 }<br />

15 }<br />

16<br />

17 public static void printPar(int count) {<br />

18 char[] str = new char[count*2];<br />

19 printPar(count, count, str, 0);<br />

20 }<br />

1 7 4

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

Saved successfully!

Ooh no, something went wrong!