| 1 | var parens = function(n) { |
| 2 | var answers = []; |
| 3 | var recurse = function(currParens, remainingPairs) { |
| 4 | if (remainingPairs === 0) { |
| 5 | answers.push(currParens); |
| 6 | } else { |
| 7 | var used = {}; |
| 8 | if (!used[`(${currParens})`]) { |
| 9 | used[`(${currParens})`] = true; |
| 10 | recurse(`(${currParens})`, remainingPairs - 1); |
| 11 | } |
| 12 | if (!used[`()${currParens}`]) { |
| 13 | used[`()${currParens}`] = true; |
| 14 | recurse(`()${currParens}`, remainingPairs - 1); |
| 15 | } |
| 16 | if (!used[`${currParens}()`]) { |
| 17 | used[`${currParens}()`] = true; |
| 18 | recurse(`${currParens}()`, remainingPairs - 1); |
| 19 | } |
| 20 | } |
| 21 | }; |
| 22 | recurse('', n); |
| 23 | return answers; |
| 24 | }; |
| 25 | |
| 26 | /* TEST */ |
| 27 | var testn = 3; |