Created
May 10, 2017 08:42
-
-
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
This file contains 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
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