这道题目可以使用dfs,即深度优先遍历。加上适当的剪枝。可以求解。搜索回溯。
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new LinkedList<>();
if (n == 0) return res;
int remainLeft = n;
int remainRight = n;
StringBuffer path = new StringBuffer();
dfs(res, remainLeft, remainRight, path);
return res;
}
private void dfs(List<String> res, int remainLeft, int remainRight, StringBuffer path) {
if (remainLeft == 0 && remainRight == 0) {
res.add(new String(path));
return;
}
if (remainLeft > 0) {
if ((remainLeft - 1) <= remainRight) {
path.append("(");
remainLeft--;
dfs(res, remainLeft, remainRight, path);
remainLeft++;
path = path.deleteCharAt(path.length() - 1);
}
}
if (remainRight > 0) {
if (remainLeft <= (remainRight - 1)) {
path.append(")");
remainRight--;
dfs(res, remainLeft, remainRight, path);
remainRight++;
path = path.deleteCharAt(path.length() - 1);
}
}
}
}