LeetCode 面试题 08.09. 括号

文章目录

一、题目

括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。

说明:解集不能包含重复的子集。

例如,给出 n = 3,生成结果为:

"((()))", "(()())", "(())()", "()(())", "()()()"

点击此处跳转题目

二、C# 题解

题目比较简单,代码如下。

csharp 复制代码
public class Solution {
    public IList<string> GenerateParenthesis(int n) {
        IList<string> ans = new List<string>();
        Partition(ans, new StringBuilder(), 0, 0, n);
        return ans;
    }

    public void Partition(IList<string> ans, StringBuilder sb, int i, int j, int n) {
        if (i == n && j == n) { // 递归出口
            ans.Add(sb.ToString());
            return;
        }
        if (i == n) { // 左括号添加完,只能添加右括号
            sb.Append(')');
            Partition(ans, sb, i, j + 1, n);
            sb.Remove(sb.Length - 1, 1); // 回溯
        }
        else { // 左、右括号都可以继续添加
            // 先添加左括号
            sb.Append('(');
            Partition(ans, sb, i + 1, j, n);
            sb.Remove(sb.Length - 1, 1); // 回溯
            
            // 如果可以添加右括号,则添加
            if (i > j) {
                sb.Append(')');
                Partition(ans, sb, i, j + 1, n);
                sb.Remove(sb.Length - 1, 1); // 回溯
            }
        }
    }
}
  • 时间:128 ms,击败 100.00% 使用 C# 的用户
  • 内存:43.50 MB,击败 83.33% 使用 C# 的用户
相关推荐
hez20106 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
聚客AI15 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v17 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工19 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
mudtools20 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
骑自行车的码农20 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了21 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo21 小时前
322:零钱兑换(三种方法)
算法
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法