LeetCode OJ:Generate Parentheses

来源:互联网 发布:淘宝维修手机可靠吗 编辑:程序博客网 时间:2024/05/29 14:32

Generate Parentheses

 

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 {    stack<char> st;    vector<string> result;    string str;public:    void dfs(int k,int n){        if(k==n){            if(st.size()==1){                result.push_back(str);            }            return;        }        char c=st.top();        if(c=='('){            str.append(")");            st.pop();            dfs(k+1,n);            str.resize(k);            st.push('(');        }        str.append("(");        st.push('(');        dfs(k+1,n);        str.resize(k);        st.pop();    }    vector<string> generateParenthesis(int n) {                st.push(')');        dfs(0,2*n);        return result;    }};


0 0
原创粉丝点击