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

Generate Parentheses

时间:2015-07-03 09:22:17      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:leetcode   generate parentheses   

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

标签:leetcode   generate parentheses   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!