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
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],布布扣,bubuko.com
LeetCode: Generate Parentheses [021]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26007139