您的位置:首页 > 其它

LeetCode 22 Generate Parentheses

2015-06-13 00:31 465 查看
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:

"((()))", "(()())", "(())()", "()(())", "()()()"


DFS 参考:http://blog.csdn.net/yangliuy/article/details/41170599

public class Solution {
public static List<String> ans;
public List<String> generateParenthesis(int n) {
ans=new ArrayList<String>();
if(n<=0)
return ans;
dfs("",n,n);
return ans;
}

public void dfs(String str,int left,int right){
if(left>right){
return ;
}
if(left==0&&right==0){
ans.add(str);
}
if(left>0){
dfs(str+"(",left-1,right);
}
if(right>0){
dfs(str+")",left,right-1);
}
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: