Generate Parentheses

来源:互联网 发布:淘宝小棉袄衣服 编辑:程序博客网 时间:2024/06/14 07:33

一、问题描述

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:    vector<string> generateParenthesis(int n) {        vector<string> v;         string s = "";        method(v, n, n, s);        return v;    }    void method(vector<string> &v, int start, int end, string s){        if(start == 0 && end == 0)            v.push_back(s);        if(start > 0)            method(v, start - 1, end, s + '(');        if(start < end)            method(v, start, end - 1, s + ')');    }};


0 0
原创粉丝点击