标签:
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对括号。输出全部可行的括号组合字符串。
所谓合法。就是能够Valid Parentheses方法评判得到true
在入栈推断的时候须要注意下面几点:
1. 当辅助栈为空时,压入左括号,而不考虑右括号
2. 当辅助栈不为空时。栈顶假设是左括号。我们能够压入左括号,或者选择压入右括号(实际上右括号并不真正压入,而是栈顶的左括号出栈与当前右括号匹配)
3. 当辅助栈不为空时,栈顶假设是右括号,仅仅能压入左括号
class Solution {
public:
bool isPair(char left, char right){
if(left==‘(‘&&right==‘)‘)return true;
return false;
}
void combination(vector<string>&result, stack<char>st, string comb, int leftPareNum, int rightPareNum){
if(leftPareNum==0&&rightPareNum==0){
result.push_back(comb);
return;
}
if(st.empty()){
//假设为空则左括号入栈
if(leftPareNum>0){
st.push(‘(‘);
combination(result,st,comb+"(",leftPareNum-1,rightPareNum);
}
}
else{
char stTop=st.top();
if(stTop==‘(‘){
if(leftPareNum>0){
st.push(‘(‘);
combination(result, st, comb+"(",leftPareNum-1,rightPareNum);
st.pop();
}
if(rightPareNum>0){
st.pop();
combination(result,st, comb+")",leftPareNum,rightPareNum-1);
}
}
else{
//栈顶为右括号,仅仅能压入左括号
if(leftPareNum>0){
st.push(‘(‘);
combination(result,st,comb+"(",leftPareNum-1,rightPareNum);
}
}
}
}
vector<string> generateParenthesis(int n) {
vector<string>result;
stack<char>st;
combination(result,st,"",n,n);
return result;
}
};版权声明:本文博主原创文章,博客,未经同意不得转载。
LeetCode: Generate Parentheses [021]
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4835254.html