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

[leetcode 22]generate parentheses

时间:2015-09-06 22:49:12      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:

1 题目:

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:

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

 

2 思路:

这道题想了好长时间,想不出解法。发现别人用递归解决的。https://leetcode.com/discuss/14436/concise-recursive-c-solution

递归是一种思想啊,一种函数思维?

感觉要完全学会并运用很不容易。

m表示左边的括号,n表示右边的括号。

3 代码:

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        helper(result,"", n, 0);
        
        return result;
    }
    
    private void helper(List<String> list,String string, int m, int n){
        if(m==0 && n==0){
            list.add(string);
            return;
        }
        
        if(m > 0) helper(list,string+"(",m-1,n+1);
        if(n > 0) helper(list,string+")",m,n-1);
    }

时间复杂度,我画递归树,发现最大时间复杂度是o(2^n),有不同意见的可以留言一起探讨。

[leetcode 22]generate parentheses

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4787450.html

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