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

#22 Generate Parentheses

时间:2015-06-02 00:02:28      阅读:275      评论: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:

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

本题是括号匹配输出,利用迭代输出。

代码如下:

class Solution {
public:
    void unguarded_generate(vector<string> &result, string curr, int m, int n){
        if (m == 0 && n == 0){
            result.push_back(curr);
        }
        else{
            if (m != 0){
                cout << curr << endl;
                unguarded_generate(result, curr + "(", m - 1, n);
            }
            if (m < n && n != 0){
                cout << curr << endl;
                unguarded_generate(result, curr + ")", m, n - 1);
            }
        }
    }

    vector<string> generateParenthesis(int n) {
        vector<string> ret;
        if (n > 0){
            unguarded_generate(ret, string(), n, n);
        }
        return ret;
    }
};

 

#22 Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/Scorpio989/p/4545075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!