您的位置:首页 > 其它

22. Generate Parentheses

2016-04-15 19:55 337 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: