[leetcode 22]generate parentheses

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),有不同意见的可以留言一起探讨。

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