码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 22 Generate Parentheses

时间:2015-06-13 01:09:41      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode 22 Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4572864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!