题解 | #括号生成#

括号生成

http://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca

栈+全排列
class Solution {
public:
    bool pan(string s){
        stack<char> m;
        for(auto p:s){
            if(m.empty()){
                m.push(p);
            }else{
                if(m.top()=='('&&p==')'){
                    m.pop();
                }else{
                    m.push(p);
                }
            }
        }
        return m.empty()?true:false;
    }
    vector<string> generateParenthesis(int n) {
        string s;
        for(int i=0;i<n;i++)
            s+='(';
        for(int i=0;i<n;i++)
            s+=')';
        vector<string> x;
        if(pan(s))
            x.push_back(s);
        while(next_permutation(s.begin(),s.end())){
            if(pan(s))
                x.push_back(s);
        }
        return x;
        
    }
};
全部评论

相关推荐

04-28 10:14
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务