括号生成
class Solution {
public static List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if (n < 0) {
return res;
}
StringBuilder path = new StringBuilder();
dfs(n, path, res, 0, 0);
return res;
}
public static void dfs(int n, StringBuilder path, List<String> res, int open, int close) {
if (path.length() == 2 * n) {
res.add(path.toString());
return;
}
if (open < n) {
dfs(n, path.append('('), res, open + 1, close);
path.deleteCharAt(path.length() - 1);
}
if (close < open) {
dfs(n, path.append(')'), res, open, close + 1);
path.deleteCharAt(path.length() - 1);
}
}
}