Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
搜索每一种可能的结果,可以使用BFS或者DFS。BFS可是考虑使用队列。但这道题更适合用DFS求解。注意helper函数接收left和right变量,作为左括号和右括号剩余数量。注意当left小于right时,属于异常情况,括号不能完整匹配,所以此时直接返回即可。另外通过变量res储存结果。
Given n = 3
, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution {
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
public ArrayList<String> generateParenthesis(int n) {
// DFS
ArrayList<String> res = new ArrayList<String>();
helper(n, n, n, "", res);
return res;
}
void helper(int n, int left, int right, String str, ArrayList<String> res) {
if(left > right) return;
if (left == 0 && right == 0) {
res.add(str);
return;
} else if (left == 0 && right != 0) {
while(right-- > 0) str += ")";
res.add(str);
return;
} else if (left != 0 && right == 0) {
return;
} else{
helper(n, left - 1, right, str + "(", res);
helper(n, left, right - 1, str + ")", res);
return;
}
}
}