括号序列问题Leetcode022括号生成(合法的括号序列的充要条件)(dfs问题)

地址

https://leetcode-cn.com/problems/generate-parentheses/submissions/

描述

在这里插入图片描述

思想

在这里插入图片描述
满足合法的括号序列的充分必要条件:

  • 括号组合中左括号的数量等于右括号的数量
  • 括号组合中任何位置左括号的数量都大于等于右括号的数量
    本题中第一个条件始终满足。
    怎么样将符合条件的结果输出:使用dfs方法
    什么时候添加 ‘(’ ? 只要 ‘(’ 数量小于n,有左括号就能放。
    什么时候添加 ‘)’ ? 首先 ')'数目小于 n,且rc<lc这样才能保证添加完后,右括号数目不会超过左括号。

代码

自己写的

class Solution {
    
    
public:
    vector<string> ans;
    string path;
    vector<string> generateParenthesis(int n) {
    
    
        dfs(n,0,0);
        return ans;
    }
    void dfs(int n,int lc,int rc){
    
    
        if(lc==n&&rc==n) {
    
    
            ans.push_back(path);
            return ;
        }
            if(lc<n){
    
    
                path.push_back('(');
                dfs(n,lc+1,rc);
                path.pop_back();
            }
            if(rc<n&&rc<lc){
    
    
                path.push_back(')');
                dfs(n,lc,rc+1);
                path.pop_back();
            }
    }
};

y总的

class Solution {
    
    
public:
    vector<string> ans;
    vector<string> generateParenthesis(int n) {
    
    
        dfs(n,0,0,"");
        return ans;
    }
    void dfs(int n,int lc,int rc,string path){
    
    
        if(lc==n&&rc==n) {
    
    
            ans.push_back(path);
            return ;
        }
            if(lc<n){
    
    
               dfs(n,lc+1,rc,path+'(');
            }
            if(rc<n&&rc<lc){
    
    
               dfs(n,lc,rc+1,path+')');
            }
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121346290