LeetCode #22 Generate Parentheses C# Solution

本文介绍了一个生成有效括号组合的算法。该算法基于递归原理,确保任何时候左括号的数量都不小于右括号的数量,从而生成所有可能的有效括号组合。

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

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.


这题如果不要输出各个结果的话那答案就是卡特兰数。

但是他要你输出了= =

可以注意到一点,就是在第n个括号放下的时候,1到n总体而言,左括号的数量大于或等于右括号。然后通过这个条件递归做就可以了。

当然实现代码的时候可以带上剩下多少个左括号多少个右括号的参数,这样比较方便。


    public class Solution
    {
        public IList<string> GenerateParenthesis(int n)
        {
            string s = "";
            generater(n, n, s);
            List<string> ans = new List<string>();
            foreach (var t in result)
            {
                ans.Add(t);
            }
            ans.Reverse(); 
            return ans;
        }
        Stack<string> result = new Stack<string>();
        void generater(int l, int r, string s)
        {
            if (l == 0 && r == 0)
            {
                result.Push(s);
            }
            if (l > 0)
            {
                generater(l - 1, r, s + '(');
            }
            if (r > 0 && l < r)
            {
                generater(l, r - 1, s + ')');
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值