Created
February 18, 2013 20:05
-
-
Save charlespunk/4980218 to your computer and use it in GitHub Desktop.
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
Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses. |
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
public static ArrayList<String> nPairsParentheses(int n){ | |
ArrayList<String> output = new ArrayList<>(); | |
nPairsParentheses(n, 0, new StringBuffer(), output); | |
return output; | |
} | |
public static void nPairsParentheses(int remindLeft, int remindRight, StringBuffer byfar, ArrayList<String> output){ | |
if(remindLeft == 0 && remindRight == 0) output.add(byfar.toString()); | |
if(remindLeft > 0){ | |
byfar.append("("); | |
nPairsParentheses(remindLeft - 1, remindRight + 1, byfar, output); | |
byfar.deleteCharAt(byfar.length() - 1); | |
} | |
if(remindRight > 0){ | |
byfar.append(")"); | |
nPairsParentheses(remindLeft, remindRight - 1, byfar, output); | |
byfar.deleteCharAt(byfar.length() - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment