Generate Parentheses
来源:互联网 发布:东湖高新人工智能峰会 编辑:程序博客网 时间:2024/06/14 09:37
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
解题思路:
1. 构造一棵包含所有情况的二叉树;
2. 根节点符号为 ‘#’,左子树为 '(',右子树为 ')';
struct Node {
char val;
Node *left;
Node *right;
Node(char c) : val(c),left(NULL),right(NULL){}
};
3. 先根遍历二叉树并得到从根节点到叶节点的符号序列保存到栈 stack<char> tmp 中(例如第一个序列是 "#((((((");
4. 判断该序列是否合法:
a. char c = tmp.top() ;
b. 判断 c 是否为左括号,若是则入 stack<char> cont,若不是则判断 c 是否和 cont 栈顶元素匹配;
c. 若 c 和 cont 栈顶元素匹配,则 cont 出栈,若不匹配则直接返回;
d. tmp 栈空后判断 cont 是否为空(即栈顶元素为 ‘#’),若为空则该序列合法,否则非法;
完整代码:
struct Node {
char val;
Node *left;
Node *right;
Node(char c) : val(c),left(NULL),right(NULL){}
};
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string>ret;
vector<string>result;
stack<char> tmp;
Node *root = new Node('#');
init(root,2*n);
travel(root,tmp,ret);
for(int i = 0 ; i < ret.size() ; i+=2)
result.push_back(ret[i]);
return result;
}
private:
void init(Node *root,int n)
{
if(n == 0) return ;
Node *left = new Node('(');
Node *right = new Node(')');
root->left = left;
root->right = right;
init(left,n-1);
init(right,n-1);
}
void travel(Node *root,stack<char> &tmp,vector<string> &ret)
{
if(root == NULL)
{
judge(tmp,ret);
return ;
}
tmp.push(root->val);
stack<char> tmpBack = tmp;
travel(root->left,tmp, ret);
travel(root->right,tmpBack,ret);
}
void judge(stack<char> &tmp,vector<string> &ret)
{
stack<char> cont;
cont.push('#');
string str;
while(!tmp.empty())
{
char c = tmp.top();
tmp.pop();
if(c == '(')
{
str.push_back(c);
cont.push(c);
}
else if(c == ')')
{
str.push_back(c);
if(cont.top() == '(') cont.pop();
else return;
}
}
if(cont.top() == '#') ret.push_back(str);
}
};
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- 欢迎使用CSDN-markdown编辑器
- 仿照JAVA vector模型写一个SuperArray
- 1115: 数字统计
- C++作业6
- Mysql create table failure: ERROR 1005 (HY000): Can't create table 'lams.attendance1' (errno: 121)
- Generate Parentheses
- eclipse安装svn插件
- CDN 技术详解--读书笔记-完
- quadratic equation
- fedora 安装eclipse和pydev以及wxpython
- UVA 1395 Slim Span--苗条的生成树(并查集+枚举)
- 发送短信(阿里云短信发送方式)
- 【剑指offer-解题系列(4)】重建二叉树
- 单元测试基础知识