[LeetCode]Generate Parentheses题解
2017-09-17 21:03
295 查看
Generate Parentheses:
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:
[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()”]
这道题的答案是很多种左右括号组合成的一个set,因为情况有很多种,所以常规的算法比较麻烦,所以采取递归的方法解决。算法的复杂度是O(n^2).
举例n>3的时候,递归的过程如下:
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:
[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()”]
这道题的答案是很多种左右括号组合成的一个set,因为情况有很多种,所以常规的算法比较麻烦,所以采取递归的方法解决。算法的复杂度是O(n^2).
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> re; recursion(re,n,0,""); return re; } void recursion(vector<string> &re,int l,int r,string str){ if(l == 0 && r == 0){ re.push_back(str); } if(r>0) recursion(re,l,r-1,str+")"); if(l>0) recursion(re,l-1,r+1,str+"(");//用掉一个左括号(l-1),可用的有括号就多了一个(r+1) } };
举例n>3的时候,递归的过程如下:
"(" / \ "((" "()" / \ / \ "(((" "(()" "()(" ** //星号处,没有可用的右括号 ...
相关文章推荐
- Leetcode: Generate Parentheses
- [LeetCode] Generate Parentheses
- leetcode 022 Generate Parentheses
- 【LeetCode】【Array】【22】Generate Parentheses
- 【leetcode】Generate Parentheses 算法解析
- 【Leetcode】【python】Generate Parentheses
- [leetcode] Generate Parentheses
- [LeetCode]Generate Parentheses
- [Leetcode] Generate Parentheses
- LeetCode 22 Generate Parentheses
- LeetCode 22 Generate Parentheses 卡特兰数问题,有待进一步学习
- leetcode—Generate Parentheses
- LeetCode: Generate Parentheses
- [LeetCode] Generate Parentheses 解题报告
- 【Leetcode】Generate Parentheses in JAVA
- LeetCode Generate Parentheses
- Generate Parentheses - Leetcode
- leetcode - Generate Parentheses
- LeetCode 22 Generate Parentheses
- [Leetcode]Generate Parentheses