Skip to content

Instantly share code, notes, and snippets.

@happyWinner
Created August 8, 2014 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyWinner/b5f342df67518297f704 to your computer and use it in GitHub Desktop.
Save happyWinner/b5f342df67518297f704 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
/**
* Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses.
*
* Time Complexity: O(2^n)
* Space Complexity: O(2^n)
*/
public class Question9_6 {
public LinkedList<String> parentheses(int n) {
LinkedList<String> parentheses = new LinkedList<String>();
recParentheses(parentheses, n, 0, 0, new StringBuffer());
return parentheses;
}
private void recParentheses(LinkedList<String> parentheses, int n, int left, int right, StringBuffer parenthese) {
if (n <= left && n <= right) {
parentheses.add(parenthese.toString());
return;
}
if (left < n) {
parenthese.append("(");
recParentheses(parentheses, n, left + 1, right, parenthese);
parenthese.deleteCharAt(parenthese.length() - 1);
}
if (right < left) {
parenthese.append(")");
recParentheses(parentheses, n, left, right + 1, parenthese);
parenthese.deleteCharAt(parenthese.length() - 1);
}
return;
}
public static void main(String[] args) {
Question9_6 question9_6 = new Question9_6();
LinkedList<String> parentheses = question9_6.parentheses(4);
for (String parenthese : parentheses) {
System.out.println(parenthese);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment