Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created June 4, 2012 15:18
Show Gist options
  • Save hpcx82/2869008 to your computer and use it in GitHub Desktop.
Save hpcx82/2869008 to your computer and use it in GitHub Desktop.
#algorithm# Given the number, print all pairs of '(' and ')'
use strict;
use warnings;
my @output;
sub printBrackets($$)
{
my ($nLeft, $nRight) = @_;
# recursion end condition
if($nLeft == 0 && $nRight == 0)
{
print join "", @output;
print "\n";
return;
}
# in any time, existing left brackets must >= right brackets
if($nLeft == $nRight)
{
push @output, "(";
printBrackets($nLeft-1, $nRight);
pop @output;
}
else
{
if($nLeft > 0)
{
push @output, "(";
printBrackets($nLeft-1, $nRight);
pop @output;
}
if($nRight > 0)
{
push @output, ")";
printBrackets($nLeft, $nRight-1);
pop @output;
}
}
}
printBrackets(1,1);
printBrackets(2,2);
printBrackets(3,3);
@hpcx82
Copy link
Author

hpcx82 commented Jun 5, 2012

perl,其实很美

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment