We can start with () and in each step three of these things
- append ()
- prefix ()
- enclose in ( … )
ex.
start - ()
iteration 1 - ()(), (()) [in this case prefix and appending with () results in same string ()()]
iteration 2 - ()()(), (()()), (())(), ()(()) ((()))
code
public static List<String> generateValidParentheses(int num) {
if(num == 0)
return Collections.emptyList();
List<String> result = new ArrayList<>();
List<String> previouslyGenerated = new ArrayList<>();
previouslyGenerated.add("()");
for(int i = 1; i < num; i++) {
int size = previouslyGenerated.size();
Set<String> newSet = new HashSet<>();
for(int j = 0; j < size; j++) {
newSet.add("()" + previouslyGenerated.get(j));
newSet.add(previouslyGenerated.get(j) + "()");
newSet.add(wrapWithParanthesis(previouslyGenerated.get(j)));
}
previouslyGenerated = new ArrayList<>(newSet);
}
return previouslyGenerated;
}