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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
做出来了 效率还行
n parenthesis => n left + n right => 2*n positions.Each time, one left or right should be chosen.
We can always pick left.
If there are more right remained, we can put right.
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> results = new ArrayList<>();
generateParenthesis(results, "", n, n);
return results;
}
public void generateParenthesis(ArrayList<String> results, String prefix, int left, int right) {
if (left == 0 && right == 0) {
results.add(prefix);
return;
}
if (left > 0) {
generateParenthesis(results, prefix+"(", left-1, right);
}
if (left < right) {
generateParenthesis(results, prefix+")", left, right-1);
}
}