22. Generate Parentheses(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84309273

题目:

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:

[   
"((()))",   
"(()())",   
"(())()",   
"()(())",   
"()()()" 
]

解释:
之前有一道类似的题,可以用栈和字典来做
解法1:递归法(二叉树递归思想)
1.插入数量不超过n
2.可以插入 ) 的前提是当前的tmp中( 的数量大于 )
 在什么情况下添加左括号呢?很明显,最多能添加n个左括号,在递归调用的时候,在能传递到最底层的共用字符串中先添加(,然后left-1,递归调用就可以。
 那什么时候添加右括号呢?当左括号个数大于右括号的个数时添加右括号。
 那我们是先添加右括号还是先添加左括号呢?对于这个问题,认真想想其实是无所谓的,只会影响在vector中最后字符串的顺序而已。
变量left和变量right表示的意思是还需要继续被添加的左括号和右括号的个数。
python代码:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        self.result=[]
        def dfs(temp,left,right):
            if not left and not right:
                self.result.append(temp)
                return
            if left>0:
                dfs(temp+'(',left-1,right)
            if left<right:
                dfs(temp+')',left,right-1)
        dfs('',n,n)
        return self.result

c++代码:

class Solution {
public:
    vector<string> result;
    vector<string> generateParenthesis(int n) {
        dfs("",n,n);
        return result;
    }
    void dfs(string tmp,int left,int right)
    {
        if(left==0 && right==0)
            result.push_back(tmp);
        if (left>0)
            dfs(tmp+"(",left-1,right);
        if (right>left)
            dfs(tmp+')',left,right-1);
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84309273
今日推荐