Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save osgix/31f268591a4d61e8d1bbb127d62da344 to your computer and use it in GitHub Desktop.
Save osgix/31f268591a4d61e8d1bbb127d62da344 to your computer and use it in GitHub Desktop.
Generating valid paranthesis (e.g. (()()), ()()(), ....) is a challenge from Cracking Code Interview Book
import java.util.LinkedList;
import java.util.List;
public class GenerateValidParanthesisPermutations {
private static final String OPEN = "(";
private static final String CLOSE = ")";
public static void main(String[] args) {
List<String> permutations = generateValidPermuations(3);
for (String permutation : permutations) {
System.out.println(permutation);
}
}
private static List<String> generateValidPermuations(int n) {
StringBuilder currentBuilder = new StringBuilder(OPEN);
return doGenerate(n*2, currentBuilder, 1, 0);
}
private static List<String> doGenerate(int n, StringBuilder currentBuilder, int openCount, int closeCount) {
List<String> permutations = new LinkedList<>();
if (closeCount == n / 2 && openCount == n / 2) {
permutations.add(currentBuilder.toString());
return permutations;
}
if (openCount < n / 2 && openCount >= closeCount) {
StringBuilder newBuilder = new StringBuilder();
newBuilder.append(currentBuilder.toString());
newBuilder.append(OPEN);
permutations.addAll(doGenerate(n, newBuilder, openCount + 1, closeCount));
}
if (closeCount < n / 2) {
StringBuilder newBuilder = new StringBuilder();
newBuilder.append(currentBuilder.toString());
newBuilder.append(CLOSE);
permutations.addAll(doGenerate(n, newBuilder, openCount, closeCount + 1));
}
return permutations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment