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

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

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

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

8.5 Implement an algorithm to print all valid (e.g., properly opened <strong>and</strong> 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 />

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, <strong>and</strong> when can we use a right paren?<br />

»»<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 />

»»<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 <strong>and</strong> right paren<strong>the</strong>ses allowed. If <strong>the</strong>re are<br />

left parens remaining, we’ll insert a left paren <strong>and</strong> 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 <strong>and</strong><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 />

CareerCup.com<br />

1 7 4

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

Saved successfully!

Ooh no, something went wrong!