Created
June 4, 2012 15:18
-
-
Save hpcx82/2869008 to your computer and use it in GitHub Desktop.
#algorithm# Given the number, print all pairs of '(' and ')'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perl,其实很美