class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
gen("", 0, 0, result, n);
return result;
}
public void gen(String sublist, int left, int right, List<String> result, int n) {
if (left < n)
gen(sublist + "(", left + 1, right, result, n);
if (left > right && right < n)
gen(sublist + ")", left, right + 1, result, n);
if (left == n && right == n)
result.add(sublist);
}
}
注:
就是递归,但是剪枝的条件需要记一下。