class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>(n);
StringBuilder path = new StringBuilder(n + n);
dfs(result, path, n, n);
return result;
}
private void dfs(List<String> result, StringBuilder path, int l, int r) {
if (l < 0 || r < 0) {
return;
}
if (l == 0 && r == 0) {
result.add(path.toString());
return;
}
if (r >= l) {
path.append('(');
dfs(result, path, l - 1, r);
path.deleteCharAt(path.length() - 1);
}
path.append(')');
dfs(result, path, l, r - 1);
path.deleteCharAt(path.length() - 1);
}
}
22. 括号生成
最新推荐文章于 2024-08-25 18:17:58 发布