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 class Solution{
public void solution(List<String> res, String s, int left, int right) {
if(left!=0){
solution(res, s + "(", left-1, right);
if(left < right)
solution(res, s + ")", left, right-1);
//left!=0,无脑递归
}else{
while(right!=0){
s = s + ")";
right--;
}
res.add(s);
//这种情况下就是把剩下的")"补上,因为题主不会直接添加指定长度重复的字符串,
//所以只能用笨方法。这里优化的话,能打败跟自己同运行时间的,大概60%的人
}
return;
}
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
solution(res, "", n, n);
return res;
}
}
括号生成算法
本文介绍了一个使用递归方法生成所有合法括号组合的算法。针对输入的整数n,该算法能够生成所有可能的由n对括号组成的合法字符串组合。文章通过具体的代码示例详细解释了递归过程及实现细节。
273

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



