22. Generate Parenthese
题目:
解答:
使用穷举形式,对((()))
形式的的初始串的第k = n-1个‘)’做穷举左移,如果左侧也为’)'或者已经移动到2 * k - 1的位置时(可以移动的最左侧),k减一,直至所有的右括号都已经移动到对应的2 * k - 1的位置,穷举结束
代码:
class Solution {public:bool CheckStringEnd(char* s, int len){for(int i = 0;i < len; ++i)if((i&1) && s[i] != ')' || !(i&1) && s[i] != '(')return false;return true;}vector<string> generateParenthesis(int n) {char s[256] = { 0 };vector<string> result;for(int i = 0;i < n;++i)s[i] = '(';for(int i = n;i < 2 * n; ++i)s[i] = ')';while(true){result.push_back(s);if(CheckStringEnd(s, 2 * n))break;// 每一个右括号,可以向前移动到的最大位置为[2k-1],其中最后一个右括号永远不可以移动// 从倒数第二个开始计算int k = n - 1;while(true){int cnt = 0, index = 0;for(int i = 0;i < 2 * n; ++i){if(s[i] == ')') ++cnt;if(cnt == k) {index = i;break;}}//如果不能swap,那么k左推1,且后面的初始化为()))类似格式if(index == 2 * k - 1 || s[index-1] == ')'){for(int i = index;i < n + k -1;++i)s[i] = '(';for(int i = n + k - 1;i < 2 * n - 1; ++i)s[i] = ')';--k;}else{swap(s[index], s[index-1]);break;}}}return result;}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)
22. Generate Parenthese相关推荐
- FTPrep, 22 Generate Parenthese
generate something, 在这里本质上就是生成一个string,按照一定的规则,这个规则就是一棵选择树,不断的向下分支,然后再融合,就是典型的DFS的方法.然后DFS方法就是典型的递归的 ...
- [leetcode] 22. Generate Parentheses
题目大意 https://leetcode.com/problems/generate-parentheses/description/ 22. Generate Parentheses Given ...
- LeetCode 22. Generate Parentheses--Python 解法--广度优先、深度优先解法
题目地址:Generate Parentheses - LeetCode Given n pairs of parentheses, write a function to generate all ...
- [leetcode] 22. Generate Parentheses(medium)
原题 思路: 利用DFS,搜索每一种情况,同时先加"("后加")",保证()匹配正确. 最近开始学习前端,尝试用js来写. const generate = f ...
- 22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [LeetCode] #22 Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- LeetCode 22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- Leetcode——Generate Parenthese
2019独角兽企业重金招聘Python工程师标准>>> 问题描述: Given n pairs of parentheses, write a function to generat ...
- leetcode : generate parenthese
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
最新文章
- PHP命名空间(Namespace)的使用详解(转)
- Java多线程面试题
- gtk linux 升级_需要在Ubuntu上更新GTK(10.04)
- python画图-如何用python画图
- NVIDIA Jetson Xavier NX上导入tensorflow报错:AttributeError: module ‘wrapt‘ has no attribute ‘ObjectProxy‘
- Docker-tag
- ZT Android4.2蓝牙基础架构学习
- 河北科技创新平台年报系统 - 头脑风暴会
- ITK:创建高斯导数内核
- 微软超融合私有云测试08-SCVMM部署之SQL Server与前置条件安装
- 51Nod1469 淋漓尽致子串
- http请求后status为canceled处理
- UNP Chapter 25 - 原始套接口
- 大数据学习总结(4)参考splunk架构
- 不敢相信?System.currentTimeMillis() 居然存在性能问题
- 韩顺平Scala精讲 最强Scala 教学视频!
- PLSQL 使用技巧(快捷键/关键字等)
- python 创意编程 全国-全国青少年创意编程与智能设计大赛Python创意编程比赛
- 应急响应之windows进程排查
- 2018下半年Android面试历程