您的位置:首页 > 其它

[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).

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的时候,递归的过程如下:

"("
/      \
"(("       "()"
/    \     /    \
"((("   "(()" "()("   **  //星号处,没有可用的右括号
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: