Parentheses(圆括号)匹配与生成

本文探讨了括号字符串的有效性验证及生成问题,通过栈结构实现括号匹配验证,并运用回溯法生成所有合法括号组合。适用于算法设计与数据结构学习。

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

20. Valid Parentheses合法括号

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

分析:本题构造一个栈,open括号进栈,close括号检查栈是否非空且栈顶元素为对应的open符号,否则返回false,结束后若栈空返回true。

class Solution {
public:
    bool isValid(string s) {
        int l = s.size();
        stack<char> st;
        for(int i=0;i<l;i++)
        {
            char c = s[i];
            if(c=='('  || c=='[' || c=='{')
                st.push(c);
            else
            {
                if(st.empty())
                    return false;
                if(c==')')
                    if(st.top() == '(')
                        st.pop();
                    else
                        return false;
                else if(c==']')
                    if(st.top() == '[')
                        st.pop();
                    else
                        return false;
                else if(c=='}')
                    if(st.top() == '{')
                        st.pop();
                    else
                        return false;
            }
        }
        if(st.empty())
            return true;
        return false;
 
    }
};

22. 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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

分析:本题可使用回溯法解决,回溯法其实就是DFS加剪枝,这里我们添加两个剪枝条件:

1.先尝试添加左括号,如果左括号数目小于n

2.再尝试添加右括号数目,如果右括号数目小于当前左括号数目

所以我们的回溯函数有五个参数,分别为:ans,当前string,left数目,right数目,n

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        backtrack(ans,"",0,0,n);
        return ans;
        
    }
    void backtrack(vector<string> &ans, string cur, int left, int right,int max)
    {
        if(cur.size()==max*2)
        {
            ans.push_back(cur);
            
            return;
        }
        if(left<max)
            backtrack(ans,cur+'(',left+1,right,max);
        if(right<left)
            backtrack(ans,cur+')',left,right+1,max);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值