zoukankan      html  css  js  c++  java
  • Generate Parentheses(组合,回溯)

    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=3,则有6个位置,每个位置可以插入'(',或者')',当n=3时,就有64中可能,只需对每一种可能作必要的筛选即可。

    代码:

    class Solution {
    private:
        char parenthesis[2];
        vector<string> res;
        int num;
    public:
        void dfs(int dep,string temp){
            if(dep==num){
                stack<char> s;
                for (int i=0;i<temp.size();++i)
                {
                    if(s.empty()) 
                        s.push(temp[i]);
                    else if(!s.empty()&&temp[i]==')'){
                        if(s.top()=='(') 
                            s.pop();
                    }else{
                        s.push(temp[i]);
                    }
                }
                if(!s.empty()) return;
                res.push_back(temp);
                return;
            }
            for (int i=0;i<2;++i)
            {
                temp.push_back(parenthesis[i]);
                dfs(dep+1,temp);
                temp.pop_back();
            }
            return;
        }
        vector<string> generateParenthesis(int n) {
            parenthesis[0]='(';
            parenthesis[1]=')';
            num=n*2;
            string temp="";
            dfs(0,temp);
            return res;
        }
    };
  • 相关阅读:
    使用母版页后台控制样式
    sql语句小综合
    sql拆分字段区分查询
    sql排名语句
    智力大冲浪(贪心)
    互斥的数(贪心)
    Crazy Search(hash)
    Frequent values(倍增RMQ)
    色板游戏(线段树)
    阶乘质因子分解(唯一分解定理)
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4216603.html
Copyright © 2011-2022 走看看