I whipped this one up in PHP, going for readability first. As I'm building the solutions from smaller solutions using recursion with a lot of duplicate requests, memoization here is a must.
Also, damn, this requires a lot of memory. At n=16 it crashes when trying to claim 2GB of memory when it already has 5GB used. I'll try to see how far I can get with some optimizations, but I'm not holding my breath on this one.
<?phpclassParenthesesGenerator{private$solutions;publicfunction__construct(){$this->solutions=[];}publicfunctionfindParentheses($n){if($n<0){thrownew\Exception('N less than zero');}if(isset($this->solutions[$n])){return$this->solutions[$n];}$solution=$this->generateSolution($n);$this->solutions[$n]=$solution;return$solution;}privatefunctiongenerateSolution($n){if($n==0){return[''];}$possibilities=[];for($i=0;$i<$n;$i++){$possibilities=array_merge($possibilities,$this->combinePossibilities($i,$n-$i-1));}return$possibilities;}privatefunctioncombinePossibilities($depth,$tailLength){$possibilities=[];$nestedPossibilities=$this->findParentheses($depth);$tailPossibilities=$this->findParentheses($tailLength);foreach($nestedPossibilitiesas$nestedPossibility){foreach($tailPossibilitiesas$tailPossibility){$possibilities[]='('.$nestedPossibility.')'.$tailPossibility;}}return$possibilities;}}$generator=newParenthesesGenerator();var_dump($generator->findParentheses(1));var_dump($generator->findParentheses(2));var_dump($generator->findParentheses(3));
It now fails with a different amount of memory allocated, but still doesn't reach 16.
With the way it grows, I'm guessing the number of strings for 16 pairs of parentheses to be around 30 million. With each string being 33 characters (16 opening + 16 closing parenthesis, + 1 null terminator) I'm looking at almost 8 GB of memory for the strings alone. No wonder my laptop can't compute it.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I whipped this one up in PHP, going for readability first. As I'm building the solutions from smaller solutions using recursion with a lot of duplicate requests, memoization here is a must.
Also, damn, this requires a lot of memory. At
n=16
it crashes when trying to claim 2GB of memory when it already has 5GB used. I'll try to see how far I can get with some optimizations, but I'm not holding my breath on this one.Yeah, here is the most memory efficient one I could think of:
It now fails with a different amount of memory allocated, but still doesn't reach 16.
With the way it grows, I'm guessing the number of strings for 16 pairs of parentheses to be around 30 million. With each string being 33 characters (16 opening + 16 closing parenthesis, + 1 null terminator) I'm looking at almost 8 GB of memory for the strings alone. No wonder my laptop can't compute it.