码迷,mamicode.com
首页 > 其他好文 > 详细

Generate Parentheses(组合,回溯)

时间:2015-01-11 16:08:58      阅读:197      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!