LeetCode OJ:Generate Parentheses

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;
    }
};


你可能感兴趣的:(LeetCode,DFS)