首页 > 其他 > 详细

Generate Parentheses(组合,回溯)

时间:2015-01-11 16:06:09      阅读:351      评论:0      收藏: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=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;
    }
};

 

Generate Parentheses(组合,回溯)

原文:http://www.cnblogs.com/fightformylife/p/4216603.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!