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

 

posted on 2015-06-13 00:31  gone~with~wind  阅读(118)  评论(0编辑  收藏  举报