首页 > 其他 > 详细

Generate Parentheses

时间:2015-07-03 09:21:34      阅读:219      评论:0      收藏:0      [点我收藏+]

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

解:直接使用回溯法


class Solution {
public:

    int left;
    int right;
    int len;
    vector<string> ret;

    void getAllParenthesis(<strong><span style="color:#ff0000;">string& str</span></strong>, int left, int right){
        if(left+right==2*len){
            ret.push_back(str);
            return ;
        }
        
        if(left<len){
           <span style="color:#ff6666;"> </span><span style="color:#ff0000;">str.push_back('(')</span><span style="color:#ff6666;">;//字符串可以直接使用push_back,pop_back函数</span>
            getAllParenthesis(str, left+1, right);
            <span style="color:#ff0000;">str.pop_back();</span>
        }
        
        if(right<left){
           <span style="color:#ff0000;"> str.push_back(')');</span>
            getAllParenthesis(str, left, right+1);
           <span style="color:#ff0000;"> str.pop_back();</span>
        }
    }

    vector<string> generateParenthesis(int n) {
        if(n<=0)
            return ret;
        len=n;
        
        string str;
        getAllParenthesis(str, 0, 0);
        return ret;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Generate Parentheses

原文:http://blog.csdn.net/jisuanji_wjfioj/article/details/46731149

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