Skip to content

Instantly share code, notes, and snippets.

@tylerchr
Created March 21, 2014 23:02
Show Gist options
  • Save tylerchr/9698302 to your computer and use it in GitHub Desktop.
Save tylerchr/9698302 to your computer and use it in GitHub Desktop.
var paren = function(n)
{
var arr = [],
decodeParens = function(code, len)
{
for (var i=0; i<len; ++i)
var open = (((code & (0x1 << i)) >> i) ? '(' : ')') + (open || '');
return open;
};
(function compute(len, sofar, bits, unbalanced) {
// we are done
if (!len && !unbalanced)
arr.push(decodeParens(sofar));
// open one more '(' if we aren't done yet
if (len)
compute(len-1, (sofar << 1) | 0x1, bits+1, unbalanced+1);
// we have an unbalanced paren... close it
if (unbalanced)
{
// console.log('unbalanced', unbalanced);
compute(len, (sofar << 1) | 0x0, bits+1, unbalanced-1);
}
})(n, 0, 0, 0);
return arr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment