Leecode 22. 括号生成 栈

原题链接:Leecode 22. 括号生成

和这道题很类似:使用dfs实现出栈的所有可能

基本思想都是给定了入栈顺序,求出栈的所有可能。
Leecode 22. 括号生成 栈_第1张图片

class Solution {
public:
    vector<string> v;
    stack<char> st;
    void dfs(string s,int num,int n)
    {
        if(n==num)
        {
            for(int i=s.size();i<num*2;i++)
                s+=')';
            v.push_back(s);
            return;
        }
        if(st.size()>0)
        {
            st.pop();//出栈
            dfs(s+')',num,n);
            st.push('(');//不出栈
        }
        if(num<n)
        {
            st.push('(');//进栈
            dfs(s+'(',num+1,n);
            st.pop();//不进栈
        }
    }
    vector<string> generateParenthesis(int n) {
        string s="";
        dfs(s,0,n);
        return v;
    }
};

你可能感兴趣的:(Leecode,c++,leetcode)