Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
backTrack(n, ans, new StringBuilder(), 0, 0);
return ans;
}
public void backTrack(int n, List<String> ans, StringBuilder str, int open, int closed) {
if (open >= n || closed >= n) {
if (n == open && n == closed) {
ans.add(str.toString());
} else if (open > n)
return;
else if (closed > n)
return;
}
if (closed < open) {
str.append(")");
backTrack(n, ans, str, open, closed + 1);
str.deleteCharAt(str.length() - 1);
}
str.append("(");
backTrack(n, ans, str, open + 1, closed);
str.deleteCharAt(str.length() - 1);
}
}