力扣22. 括号生成

Posted 幽殇默

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣22. 括号生成相关的知识,希望对你有一定的参考价值。

在这里插入图片描述
题目地址

class Solution {
public:
    vector<string> ve;
    vector<string> generateParenthesis(int n) {
        dfs(1,n,"");
        return ve;
    }
    void dfs(int index,int n,string s)
    {
	    if(index==n*2+1)
	    {
		    stack<char>st;
		    for(int i=0;i<s.size();i++)
		    {
			    if(st.size())
			    {
			    	if( st.top()=='('&&s[i]==')') st.pop();
				    else st.push(s[i]);
			    }
			    else st.push(s[i]);
		    }
		    if(st.size()==0) ve.push_back(s);
		    return ;
	    }
	    dfs(index+1,n,s+"(");
	    dfs(index+1,n,s+")");
    }
};

y总方法:
在这里插入图片描述

class Solution {
public:
    vector<string> ve;
    vector<string> generateParenthesis(int n) {
        dfs(n,0,0,"");
        return ve;
    }
    void dfs(int n,int l,int r,string s)
    {
	    if(l==n&&r==n) ve.push_back(s);
        else
        {
            if(l<n) dfs(n,l+1,r,s+"(");
            if(l>r) dfs(n,l,r+1,s+")");//左括号数量大于右括号
        }
    }
};

以上是关于力扣22. 括号生成的主要内容,如果未能解决你的问题,请参考以下文章

22.括号生成

leetcode-22括号生成

括号生成--力扣

[LeetCode] 22. 括号生成(回溯/DP)

力扣刷题:括号生成(java实现)

力扣刷题:括号生成(java实现)