[leetcode22] 括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

这道题最初打算用最死板的方法去做,但是写的过程中发现复杂度太高而且很繁琐。然后参考了一下别人递归的思路很快就写出来了。

python:

class Solution:
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = []
        self.add("", res, n, n)
        return res
    def add(self, string, res, l, r):
        if l > r:
            return
        if l > 0:
            self.add(string + '(', res, l - 1, r)
        if r > 0:
            self.add(string + ')', res, l, r - 1)
        if l == 0 and r == 0:
            res.append(string)
            return

C++: 

C++刚开始用值传递的时候一直返回空列表,调试了一下初步确定是因为值传递的原因就换成了地址传递。估计原因是值传递在返回时销毁了变量res,所以才会出现这种情况。

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        add("", &res, n, n);
        return res;
    }
    void add(string s, vector<string>* res, int l, int r){
        if(l > r) return;
        if(l > 0) add(s + "(", res, l - 1, r);
        if(r > 0) add(s + ")", res, l, r - 1);
        if(l == 0 && r == 0){
            (*res).push_back(s);
            return;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/84260270