LeetCode: Generate Parentheses [021]

151 篇文章 0 订阅

【题目】

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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值