LeetCode: Generate Parentheses [021]

【称号】

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


【思路】

    DFS是生成组合的第一选择。维护一个栈来辅助推断。
    依据题意,候选的括号组合为n个左括号和n个右括号,我们要生成一个长度为2n的字符串
    字符串每一位上的元素仅仅有两种选择,要么左括号。要么右括号。


    在入栈推断的时候须要注意下面几点:
    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;
    }
};


版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/gcczhongduan/p/4835254.html