Generate Parentheses(Medium)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
解题思路:回溯+DFS
- 如果左括号数还没有用完,那么我们能继续放置左括号
- 如果已经放置的左括号数大于已经放置的右括号数,那么我们可以放置右括号 (如果放置的右括号数大于放置的左括号数,会出现不合法组合)
- 返回条件: 左括号和右括号都用完的情况下返回
- 参数传入: 如果左侧增加一个括号 下次递归时候就是left- 1 右侧同理
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
if (n <= 0) {
return res;
}
StringBuilder tmp = new StringBuilder();
helper(res, n, n, tmp);
return res;
}
public void helper(List<String> res, int left, int right, StringBuilder tem) {
if (left == 0 && right == 0) {
res.add(tem.toString());
return;
}
if (left > 0) {
tem.append("(");
helper(res, left - 1, right, tem);
tem.deleteCharAt(tem.length()-1);
}
if (right > left) {
tem.append(")");
helper(res, left, right - 1,tem);
tem.deleteCharAt(tem.length()-1);
}
}