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:
"((()))", "(()())", "(())()", "()(())", "()()()"
public List<String> generateParenthesis(int n) {
if (n <= 0) {
return new ArrayList<String>();
}
ArrayList<String> rt = new ArrayList<String>();
dfs(rt, "", n, n);
return rt;
}
void dfs(ArrayList<String> rt, String s, int left, int right) {
if (left > right) {
return;
}
if (left == 0 && right == 0) {
rt.add(s);
}
if (left > 0) {
dfs(rt, s + "(", left - 1, right);
}
if (right > 0) {
dfs(rt, s + ")", left, right - 1);
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。