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:
"((()))", "(()())", "(())()", "()(())", "()()()"
之前在[url=http://kickcode.iteye.com/blog/2264122]Parentheses总结 [/url]讲过这道题目,用回溯法解决,想看更多类似的题目可以参考上面那篇文章。代码如下:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
之前在[url=http://kickcode.iteye.com/blog/2264122]Parentheses总结 [/url]讲过这道题目,用回溯法解决,想看更多类似的题目可以参考上面那篇文章。代码如下:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
int left = n;
int right = n;
generateP(2 * n, left, right, "", list);
return list;
}
public void generateP(int n, int left, int right, String s, List<String> list) {
if(s.length() == n) list.add(s);
if(left > 0) generateP(n, left - 1, right, s + '(', list);
if(right > left) generateP(n, left, right - 1, s + ')', list);
}
}
本文介绍了一种使用回溯法生成所有合法括号组合的算法。针对输入的整数n,该算法能有效生成所有可能的合法括号组合,并提供了一个具体的Java实现案例。
2043

被折叠的 条评论
为什么被折叠?



