Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For a given <code>N</code> we always have to start with an open brace. Now consider where it's corresponding closing brace is. It can be in the middle like in <code>()()</code> or at the end like <code>(())</code> for <code>N=2</code>.</p> <p>Now consider <code>N=3</code>:</p> <p>It can be at the end: <code>(()())</code> and <code>((()))</code>.</p> <p>Or in the middle: <code>()(())</code> and <code>()()()</code> where it's in position 2. Then it can also be in position 4: <code>(())()</code>.</p> <p>Now we can essentially combine the 2 cases by realising the case where the closing brace is at the end is the same as it being at the middle, but with all the possibilities for N=0 added to the end.</p> <p>Now to solve it you can work out all the possibilities for <code>n</code> between the begin and end brace and similarly you can work out all the possibilities for <code>m</code> after the end brace. (Note <code>m+n+1 = N</code>) Then you can just combine all possible combinations, append them to your list of possibilities and move on to the next possible location for the end brace.</p> <p>Just be warned an easy mistake to make with these types of problems, is to find all the possibilities for <code>i</code> and for <code>N-i</code> and just combine them, but this for <code>N=3</code> would double count <code>()()()</code> or at least print it twice.</p> <p>Here is some Python 2.x code that solves the problem:</p> <pre><code>memoise = {} memoise[0] = [""] memoise[1] = ["()"] def solve(N, doprint=True): if N in memoise: return memoise[N] memoise[N] = [] for i in xrange(1,N+1): between = solve(i-1, False) after = solve(N-i, False) for b in between: for a in after: memoise[N].append("("+b+")"+a) if doprint: for res in memoise[N]: print res return memoise[N] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload