leetcode 22 -- Generate Parentheses

本文介绍了一种生成合法括号组合的算法。针对给定的括号对数n,通过递归方式构造所有可能的合法括号组合。文章详细解释了确保左括号数量始终不少于右括号数量的原则,从而保证生成的字符串符合括号匹配规则。

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

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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”


题意:
给出括号对数,任意组合,找出所有满足括号匹配原则的字符串。


思路:
考虑出规律即可,规律就是我们要在字符串的任意时刻保证左括号“(”的数目大于右括号的数目“)”即可。^_^


代码:

class Solution {
public:
    void addRetStr(int leftNum, int rightNum, string s, vector<string>&ivecs){
        if(leftNum == 0 && rightNum == 0){
            ivecs.push_back(s);
        }
        //左括号数目等于右括号数目立即添加左括号来保证规则。
        if(leftNum == rightNum){
            s += "(";
            addRetStr(leftNum-1, rightNum, s, ivecs);
        }else{
            if(leftNum > 0){
                //注意这里参数必须是new string而不能s += "("然后传递参数s,因为还有别的string要用s。
                string new_str = s + "(";
                addRetStr(leftNum-1, rightNum, new_str, ivecs);
            }
            if(rightNum > 0){
                string new_str = s + ")";
                addRetStr(leftNum, rightNum-1, new_str, ivecs);
            }
        }
    }

    vector<string> generateParenthesis(int n) {
        string s;
        vector<string>ret;
        addRetStr(n, n, s, ret);
        return ret;
    }
};

虽然很晚了强迫症还是要写完今天的博客,哈哈
最后 祝自己20岁生日快乐^_^,感谢父母带我来这个世界,感谢我的每一位家人,朋友,加油
life's battle doesn't always go to the stronger or faster man
but sooner or later the man who wins
is the man who thinks he can...


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值