回溯
java
class Solution {
List<String> res = new ArrayList<>();
StringBuilder path = new StringBuilder(); // path推荐这种写法
public List<String> generateParenthesis(int n) {
backtrack(n, 0, 0);
return res;
}
void backtrack(int n, int l, int r){
if(r > l || l > n || r > n) return;
if(l == n && r == n){
res.add(path.toString());
return;
}
path.append('(');
backtrack(n, l + 1, r);
path.deleteCharAt(path.length() - 1);
path.append(')');
backtrack(n, l, r + 1);
path.deleteCharAt(path.length() - 1);
}
}