
这道题目是一道回溯题,特殊之处在于右括号选择时,右括号的当前数量必须少于左括号的数量
java
class Solution {
private List<String> result;
private void generateParenthesis(int n, StringBuilder stringBuilder, int open, int close) {
if (2*n == stringBuilder.length()) {
result.add(stringBuilder.toString());
}
if (open < n) {
stringBuilder.append('(');
generateParenthesis(n, stringBuilder, open + 1, close);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
if (close < open) {
stringBuilder.append(')');
generateParenthesis(n, stringBuilder, open, close + 1);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
}
public List<String> generateParenthesis(int n) {
result = new ArrayList<>();
generateParenthesis(n, new StringBuilder(), 0, 0);
return result;
}
}