LeetCode "Generate Parentheses"

DFS and using stack to validate candidates.

class Solution {
public:
    bool isValid(const string &s)
    {
        stack<char> stk;
        for (int i = 0; i < s.length(); i++)
        {
            switch (s[i])
            {
            case '(': 
                stk.push('(');
                break;
            case ')' :
                if (!stk.empty())
                {
                    if (stk.top() == '(')
                    {
                        stk.pop();
                        continue;
                    }                    
                }
                return false;
                break;
            }
        }
        return stk.empty();
    }

    void go(string s, int n, vector<string> &ret)
    {
        if (s.length() == n * 2 )
        {
            if (isValid(s))        ret.push_back(s);
            return;
        }
        go(s + "(", n, ret);
        go(s + ")", n, ret);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> rec;
        go("(", n, rec);
        return rec;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3858006.html