首页 > 其他 > 详细

LeetCode Generate Parentheses

时间:2015-02-09 14:07:45      阅读:294      评论: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:

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

题意:给你左右括号的个数,问你可以组成完全匹配的个数。

思路:递归:也就两种选择,要么左括号,要么右括号,分别记录个数;只要左括号的个数大于0的话,那么就可以填写左括号;右括号的话,那么要确保此时的序列,左括号的个数要大于右括号的个数。

class Solution {
public:

    void print(int left, int right, string s, vector<string> &result) {
        if (left == 0 && right == 0) {
            result.push_back(s);
        }

        if (left > 0) {
            print(left-1, right, s+'(', result);
        }

        if (right > 0 && left < right) {
            print(left, right-1, s+')', result);
        } 
    }

    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string tmp = "";
        print(n, n, tmp, result);
        return result;
    }
};




LeetCode Generate Parentheses

原文:http://blog.csdn.net/u011345136/article/details/43669955

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