当前位置: 首页 > news >正文

LeetCode LCR 085.括号生成

正整数 n 代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:

输入:n = 1
输出:[“()”]

提示:

1 <= n <= 8

法一:直接生成由’(‘和’)'组成的全部可能的字符串,然后再一个一个判断是否合法:

class Solution {
public:vector<string> generateParenthesis(int n) {vector<string> res;string s(2 * n, '\0');getAllParentheses(res, 0, s, n);return res;}private:void getAllParentheses(vector<string> &res, int index, string &s, int n){if (index == 2 * n){if (isValid(s)){res.push_back(s);}return;}s[index] = '(';getAllParentheses(res, index + 1, s, n);s[index] = ')';getAllParentheses(res, index + 1, s, n);}bool isValid(string &s){int cnt = 0;for (char c : s){if (c == '('){++cnt;}else{--cnt;}if (cnt < 0){return false;}}return cnt == 0;}
};

此方法时间复杂度为O(n2 2 n ^{2n} 2n);空间复杂度为O(n),最多递归2n层。很差的方法。

法二:递归求解即可:

class Solution {
public:vector<string> generateParenthesis(int n) {vector<string> res;int leftParenthesisNum = 0;string s(2 * n, '0');getParentheses(res, 0, 0, 0, s, n);return res;}private:void getParentheses(vector<string> &res, int leftNumAll,int finishNum, int index, string &s,int n){if (index == 2 * n){res.push_back(s);}if (leftNumAll < n){s[index] = '(';getParentheses(res, leftNumAll + 1, finishNum, index + 1, s, n);}if (finishNum < leftNumAll){s[index] = ')';getParentheses(res, leftNumAll, finishNum + 1, index + 1, s, n);}}
};

在这里插入图片描述
法三:我们可以把生成的结果看做(a)b,其中a和b分别是合法括号串。我们枚举每个右括号,分别计算枚举过程中a和b的内容,并且可以把特定长度的a和b的内容缓存下来:

class Solution {
public:vector<string> generateParenthesis(int n) {vector<vector<string>> cache(9);cache[0] = {""};return generate(n, cache);}private:vector<string> generate(int n, vector<vector<string>> &cache){if (cache[n].size() != 0){return cache[n];}vector<string> cur;for (int i = 0; i < n; ++i){vector<string> left = generate(i, cache);vector<string> right = generate(n - 1 - i, cache);for (string &sleft : left){for (string &sright : right){cur.push_back("(" + sleft + ")" + sright);}}cache[n] = cur;}return cache[n];}
};

在这里插入图片描述

http://www.lryc.cn/news/306523.html

相关文章:

  • 抖音视频评论数据提取软件|抖音数据抓取工具
  • 【web】云导航项目部署及环境搭建(复杂)
  • 软件测试人员必会的linux命令
  • Mac使用K6工具压测WebSocket
  • 小程序--vscode配置
  • linux僵尸进程
  • 【web | CTF】攻防世界 Web_php_unserialize
  • Vue3中的select 的option是多余的?
  • 考研408深度分析+全年规划
  • 【算法笔记】ch01_01_0771 宝石与石头
  • jQuery瀑布流画廊,瀑布流动态加载
  • 玩转ChatGPT:参考文献速查
  • [设计模式Java实现附plantuml源码~行为型]算法的封装与切换——策略模式
  • ​【C语言】长篇详解,字符系列篇3-----strstr,strtok,strerror字符串函数的使用【图文详解​】
  • 如何实现一个K8S DevicePlugin?
  • Android LruCache源码分析
  • 如何使用Inno Setup制作Unity构建程序的Windows安装程序
  • linux 面试题
  • 嵌入式中逻辑分析仪基本操作方法
  • ONLYOFFICE 桌面编辑器 v8.0 更新内容详细攻略
  • 2024-2-22 作业
  • 2.1 RK3399项目开发实录-升级固件介绍(物联技术666)
  • Uniapp + VUE3.0 实现双向滑块视频裁剪效果
  • 【算法小讲堂】#1 贪心算法
  • 判断当前shell版本
  • 如何实现两个电脑之间通过以太网(网线)实现文件互传
  • Jenkins 中部署Nodejs插件并使用,并构建前端项目(3)
  • VUE为什么有的属性要加冒号
  • 微信小程序 --- wx.request网络请求封装
  • 通义千问Qwen-7B-Chat Windows本地部署教程-详细认真版