generate-parentheses

来源:互联网 发布:java 线程面试题 编辑:程序博客网 时间:2024/06/01 07:24

题目:

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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

程序:

class Solution {public:    vector<string> generateParenthesis(int n) {        string s;        set<string> temp;//去重        vector<string> res;        stack<char> st;        for (int i = 0; i < n; i++)            s = s + "()";        sort(s.begin(), s.end());//使用next_permutation之前需要进行排序处理,否则个数会减少        do        {            temp.insert(s);        } while (next_permutation(s.begin(), s.end()));        for (auto it = temp.begin(); it != temp.end(); ++it)        {            string ss = *it;            int i = 0;            for (; i < ss.size(); i++)            {                if (ss[i] == '(')                    st.push(')');                else if (st.empty())                    break;                else                {                    st.pop();                }            }            if (i == ss.size())                res.push_back(ss);        }        return res;    }};

点评:

在next_permutation之前必须要排序,采用set去重,这题主要采用排列组合的思想,先把所有可能列出,然后在剔除。

原创粉丝点击