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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Java
因为右括号的数量不会大于左括号的数量,所以用两个计数器表示当前字符串中每种括号有几个,然后递归实现。效率在后1/3
public class Solution {
List<String> result = new ArrayList<String>();
int maxCount;
public List<String> generateParenthesis(int n) {
maxCount = n;
getString("", 0, 0);
return result;
}
public void getString(String s,int left,int right){
if(left == maxCount && right == maxCount){
result.add(s);
return;
}
if(left < maxCount){
getString(s+"(", left+1, right);
}
if(right < left){
getString(s+")", left, right+1);
}
}
}