public static List<String> generateValidParentheses(int num) {
LinkedList<String> result = new LinkedList<String>();
if(num < 1) {
return result;
}
result.add("()");
String tmp = "";
Set<String> tr = new HashSet<>();
for(int i = 1; i < num; i++) {
int count = result.size();
for(int j = 0; j < count; j++) {
tmp = result.removeFirst();
add(result, tmp, tr);
}
}
return result;
}
public static void add(List<String> res, String str, Set<String> tr) {
String tmp = "";
for(int i = 0; i < str.length(); i++) {
tmp = str.substring(0, i+1) + "()" + str.substring(i+1);
if(!tr.contains(tmp)) {
tr.add(tmp);
res.add(tmp);
}
}
}
Type your question above this line.
Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5753264117121024