java:
回溯:记录左右括号的数量,左括号小于n就继续加左括号,右括号比左括号少就加右括号,最后在path的结果等于2*n就收集结果。
class Solution {
List<String> res;
StringBuilder path;
public List<String> generateParenthesis(int n) {
res = new ArrayList<>();
path = new StringBuilder();
backTracking(0, 0, n);
return res;
}
public void backTracking(int lefNum, int rigNum, int n) {
if (lefNum + rigNum == 2 * n) {
res.add(path.toString());
return ;
}
if (lefNum < n) {
path.append("(");
backTracking(lefNum + 1, rigNum, n);
path.delete(path.length() - 1, path.length());
}
if (lefNum > rigNum) {
path.append(")");
backTracking(lefNum, rigNum + 1, n);
path.delete(path.length() - 1, path.length());
}
}
}