Leetcode 22 - Generate Parentheses(dfs)

本文介绍两种生成合法括号序列的算法实现。一种是通过深度优先搜索并利用栈检查合法性;另一种是在搜索过程中确保括号配对正确。两种方法均采用递归方式构造所有可能的合法括号组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

给定一个n,求由n个左括号和n个右括号组成的合法括号序列。

思路

算法1

直接暴力dfs,直接枚举当前位置为’(‘还是’)’,递归终点用栈判断结果是否合法。

算法2

在dfs的时候就保证结果的合法性。

括号序列的基本格式就下面两种:

  1. 相邻,()()
  2. 相互嵌套,(())

从上面的格式我们可以知道:

  1. 对左括号没有要求,只要小于等于n即可。
  2. 对右括号,任何时候右括号的数目就应该小于等于左括号的数目。

从上面的条件我们构造出dfs即可。

代码

algorithm 1

class Solution {
private:
    int n;
    vector<string> ans;
public:
    bool check(string s) {
        stack<char> st;
        for (auto c : s) {
            if (c == ')') {
                if (!st.empty() && st.top() == '(') st.pop();
                else return false;
            } else {
                st.push(c);
            }
        }
        return st.empty() ? true : false;
    }

    void dfs(string s, int i, int j) {
        if (i == n && j == n) {
            if (check(s)) ans.push_back(s);
            return;
        }
        if (i < n) {
            s.push_back('(');
            dfs(s, i + 1, j);
            s.pop_back();
        }
        if (j < n) {
            s.push_back(')');
            dfs(s, i, j + 1);
            s.pop_back();
        }
    }

    vector<string> generateParenthesis(int n) {
        this->n = n;
        dfs("", 0, 0);
        return ans;
    }
};

algorithm 2

class Solution {
private:
    int n;
    vector<string> ans;
public:
    void dfs(string s, int i, int j) {
        if (i == n && j == n) {
            ans.push_back(s);
            return;
        }
        if (i < n) dfs(s + '(', i + 1, j);
        if (j < i) dfs(s + ')', i, j + 1);
    }

    vector<string> generateParenthesis(int n) {
        this->n = n;
        dfs("", 0, 0);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值