1 题目
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
2 分析
题目要生成所有特定长度的有效括号组合,可以发现,该问题可以分解为多个子问题,即长度为n的括号组合可以由长度为n-1的括号组合生成。因此可以使用递归方法解体,递归树如下图所示:
在递归的过程中,如果出现下面两种情况,则说明以该节点为顶点的子树中一定不会存在有效的括号组合:
- 左括号的数目大于n
- 出现了单独的右括号
此时回溯。当节点的长度为2n时候,即为题目所求的括号有效组合。
3 代码
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
helper(result, "(", n);
return result;
}
private void helper(List<String> res, String str, int n){
if(!isValid(str,n)){
return;
}
if(str.length() == 2*n){
res.add(str);
return;
}
helper(res, str + "(", n);
helper(res, str + ")", n);
}
private boolean isValid(String str, int n){
LinkedList<String> stack = new LinkedList<>();
int numOfLeftPa = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == '('){
if(numOfLeftPa >= n){
return false;
}
stack.push("(");
numOfLeftPa++;
}else{
if(stack.size() == 0){
return false;
}
stack.pop();
}
}
return true;
}
}