Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 18, 2013 20:05
Show Gist options
  • Save charlespunk/4980218 to your computer and use it in GitHub Desktop.
Save charlespunk/4980218 to your computer and use it in GitHub Desktop.
Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses.
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