22. Generate Parentheses

来源:互联网 发布:原油投资网络骗局 编辑:程序博客网 时间:2024/06/14 04:30

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:

[  "((()))",  "(()())",  "(())()",  "()(())",  "()()()"]
即给出n对括号,穷举它们所有合法的排列形式。

一开始傻傻的以为,若n-1对括号的排列情况为(…),那么,n对括号的排列情况为:()(...)、(...)() 和 ((...)) ,这在n=3的时候是适用的,两对括号有两种情况:()() 和 (()) ,那么,按照这个想法,三对括号就是:()()(),(()()), ()()(),()(()), ((())), (())() ,除去其中重复的一个,就是五种情况。然而到了n=4的时候,会出现(())(()),这种情况不能由上述三种变换得到,因此需要另寻它路。

可以将不同的情况视为一棵二叉树从根到叶子的不同路径,而我们可以通过递推来列举这些路径,在递推函数parenthesisRec的参数中,res表示最后要返回的string类型向量,str表示当前生成的括号串,n就是给定的括号对数,布尔型变量LorR表示添加左括号(1)或者添加右括号(0),cnt记录已添加的左括号和右括号的差值。递推过程为,首先根据LorR的值在str后面插入一个括号,注意到n的作用是记录还有多少个未添加的左括号。然后再判断,如果n和cnt都为0,那么表示生成完毕,将str添加到结果中,否则继续插入,注意插入过程中右括号的数量不能大于左括号,即必须保证cnt>0时才能插入右括号。


class Solution {public:vector<string> generateParenthesis(int n) {vector<string> res;parenthesisRec(res, "", n, 1, 0);return res;}void parenthesisRec(vector<string> &res, string str, int n, bool LorR, int cnt) {if (LorR) {str.append("(");cnt++;n--;}else {str.append(")");cnt--;}if (n == 0 && cnt == 0) res.push_back(str);else {if (n > 0) parenthesisRec(res, str, n, 1, cnt);if (cnt > 0) parenthesisRec(res, str, n, 0, cnt);}}};




0 0