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

in <strong>the</strong> set (<strong>the</strong> “yes” state) or (2) <strong>the</strong> element is not in <strong>the</strong> set (<strong>the</strong> “no” state). This means<br />

that each subset is a sequence of yesses / nos—e.g., “yes, yes, no, no, yes, no”<br />

»»<br />

This gives us 2^n possible subsets. How can we iterate through all possible sequences<br />

of “yes” / “no” states for all elements? If each “yes” can be treated as a 1 <strong>and</strong> each “no” can<br />

be treated as a 0, <strong>the</strong>n each subset can be represented as a binary string.<br />

»»<br />

Generating all subsets <strong>the</strong>n really just comes down to generating all binary numbers<br />

(that is, all integers). Easy!<br />

1 ArrayList getSubsets2(ArrayList set) {<br />

2 ArrayList allsubsets =<br />

3 new ArrayList();<br />

4 int max = 1 0) {<br />

10 if ((k & 1) > 0) {<br />

11 subset.add(set.get(index));<br />

12 }<br />

13 k >>= 1;<br />

14 index++;<br />

15 }<br />

16 allsubsets.add(subset);<br />

17 }<br />

18 return allsubsets;<br />

19 }<br />

CareerCup.com<br />

1 7 2

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

Saved successfully!

Ooh no, something went wrong!