leetcode 22. Generate Parentheses

来源:互联网 发布:淘宝子账号干嘛的 编辑:程序博客网 时间:2024/04/30 17:08

题意

生成n对正确形式的括号序列

题解

主要由next_permutation生成全排列后判断各个字符串是否满足(isOK)。

代码

class Solution {public:    bool isOK(string str)    {        stack<int> st;        int len = str.length();        for(int i = 0; i < len; i++)        {            if(str[i] == '(')                st.push(str[i]);            else if(!st.empty() && st.top() == '(')                st.pop();            else                return false;        }        if(st.empty())            return true;        else            return false;    }    vector<string> generateParenthesis(int n) {        string str1(n, '(');        string str2(n, ')');        string str = str1 + str2;        vector<string> result;        do        {            if(isOK(str))                result.push_back(str);        }while(next_permutation(str.begin() + 1, str.end() - 1)); //string must begin with '(' and end with ')', so can duduce two elements        return result;    }};
0 0
原创粉丝点击