Problem
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Solution
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
helper(0, 0, n, "", res);
return res;
}
private void helper(int left, int right, int total, String str, List<String> res) {
if (str.length() == total*2) {
res.add(str);
return;
}
if (left < total) {
helper(left+1, right, total, str+"(", res);
}
if (right < left) {
helper(left, right+1, total, str+")", res);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。