Given
(
and)
and length of 4, generate the following combinations -()()
and(())
.
Looking for code review, optimizations and best practices. Also verifying complexity to be O(2(n+1) - 1), where n is half the 'input length'.
public final class BraceCombinations {
private BraceCombinations() {}
/**
* Returns sets of valid combinations.
*
* @param length the sum of length of all- opening + closing braces
* @return the valid brace combinations
*/
public static List<List<String>> getBraceCombinations(int length) {
if (length <= 0) {
throw new IllegalArgumentException("The length should be greater than zero");
}
if (length % 2 == 1) {
throw new IllegalArgumentException("The length should be positive");
}
final List<List<String>> paranthesesCombo = new ArrayList<List<String>>();
generate(paranthesesCombo, new LinkedList<String>(), 0, 0, length/2);
return paranthesesCombo;
}
private static void generate(List<List<String>> paranthesesCombo, LinkedList<String> parenthesis, int openBrace, int closeBrace, int halfLength) {
if (openBrace == halfLength && closeBrace == halfLength) {
paranthesesCombo.add(new ArrayList<String>(parenthesis));
}
if (openBrace > halfLength || closeBrace > openBrace) {
return;
}
parenthesis.add("(");
generate(paranthesesCombo, parenthesis, openBrace + 1, closeBrace, halfLength);
parenthesis.removeLast();
parenthesis.add(")");
generate(paranthesesCombo, parenthesis, openBrace, closeBrace + 1, halfLength);
parenthesis.removeLast();
}
public static void main(String[] args) {
List<List<String>> paths1 = Arrays.asList(
Arrays.asList("(", ")")
);
assertEquals(paths1, getBraceCombinations(2));
List<List<String>> paths = Arrays.asList(
Arrays.asList("(", "(", ")", ")"),
Arrays.asList("(", ")", "(", ")")
);
assertEquals(paths, getBraceCombinations(4));
}
}