**Input:** n = 3
**Output:** ["((()))","(()())","(())()","()(())","()()()"]
**Input:** n = 1
**Output:** ["()"]
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
process(0, 0, n, new StringBuilder(), res);
return res;
}
private void process(int left, int right, int n, StringBuilder sb, List<String> res) {
if (left == n && right == n) {
res.add(sb.toString());
}
if (left < n) {
sb.append("(");
process(left + 1, right, n, sb, res);
sb.setLength(sb.length() - 1);
}
if (right < n && left > right) {
sb.append(")");
process(left, right + 1, n, sb, res);
sb.setLength(sb.length() - 1);
}
}
}
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public void backtrack(List<String> list, String str, int open, int close, int max){
if(str.length() == max*2){
list.add(str);
return;
}
if(open < max)
backtrack(list, str+"(", open+1, close, max);
if(close < open)
backtrack(list, str+")", open, close+1, max);
}
}