LeetCode 题解(Week15):22. Generate Parentheses
来源:互联网 发布:c语言fprintf 编辑:程序博客网 时间:2024/06/05 07:31
原题目
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:
[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()” ]
中文大意
给定一个整数n,表示n对括号,需要我们生成这n对括号组成的、有效的、所有字符串,比如当n=3,需要生成: “((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题解
class Solution {public: vector<string> res; bool check(string str) { int left = 0; // cout << str <<endl; for(int i =0 ;i < str.size();i++) { if(str[i]=='(') left++; else if(str[i]==')') left--; if(left<0) return false; } return true; } void recursive(int left,int right, int n, string curr) { if(left>n || right>n) return; // cout <<left<<" "<<right<<endl; if(left < n) { recursive(left+1,right,n,curr+"("); recursive(left,right+1,n,curr+")"); } else if(right <n) recursive(left,right+1,n,curr+")"); else if(check(curr)) res.push_back(curr); } vector<string> generateParenthesis(int n) { string curr = "("; recursive(1,0,n,curr); return res; }};
思路
典型的DFS(回溯)问题,用递归的方式解决,递归函数的输入包括(left,right,n,curr):
- left——当前字符串左括号个数
- right——当前字符串右括号个数
- curr——当前字符串
- n——题目的输入
递归的过程如下:
- 初始化状态:(1,0,n,”(“),因为所有的合法字符串都从左括号开始,最左边的字符不可能是又括号
- 边界条件:当前的left或者right大于n,直接返回
- 递归实现:先判断当前的left是否小于3,如果是的话,递归(left+1,righr,n,curr+”(“)以及(left+1,righr,n,curr+”)”),相当于“下一个元素既可能是左括号又可能是右括号”
- 若left已经等于3,而right<3递归(left+1,righr,n,curr+”)”),意思是“左括号已经用完了,接下来的只可能是右括号”
- 若left等于3且right等于3,则判断这个字符串是否一个合法的括号对,如果合法,就加入到结果中
阅读全文
0 0
- LeetCode 题解(Week15):22. Generate Parentheses
- LeetCode题解:Generate Parentheses
- LeetCode题解:Generate Parentheses
- [LeetCode]Generate Parentheses题解
- 22. Generate Parentheses 题解
- 22. Generate Parentheses题解
- LeetCode 题解(179): Generate Parentheses
- LeetCode 22. Generate Parentheses 题解 —— Java
- [LeetCode]22.Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode 22.Generate Parentheses
- [Leetcode] 22. Generate Parentheses
- 【LeetCode】22.Generate Parentheses
- [leetcode] 22.Generate Parentheses
- 【leetcode】22. Generate Parentheses
- Leetcode-22.Generate Parentheses
- [leetcode] 22. Generate Parentheses
- 22. Generate Parentheses LeetCode
- 程序的机器级表示(二) 学会汇编~
- linux内核的编译(2.6.39.4)
- textarea换行
- ubuntu卸载多余的内核
- matlab中imwrite函数
- LeetCode 题解(Week15):22. Generate Parentheses
- 认识Volley的用途
- 关于IllegalMonitorStateException异常:
- 内存流的使用
- Jupiter notebook中设定kernel为python2和python3
- VB技巧【批量注释代码】【数据转换层字符串补0】【VB中的除法】【修改窗口标题与EXE图标】【TextBox控件的缺点】
- ecryptfs加密
- TensorFlow个人学习(训练 MNIST 数据 )
- dm-crypt加密