LeetCode 22.Generate Parentheses

来源:互联网 发布:网络言论自由的案例 编辑:程序博客网 时间:2024/05/01 04:36

题目:

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,代表括号数目,题目要求输出所有可能的合理组合。先扯一句题外话,所有可能的组合的个数是一个catalan数,在组合数学中是一个经典的概念。这个题和之前的17题很像,但是如果用递归的话,如何对合法性进行判断是一个难点。其实可以看出,如果把左括号看做-1,右括号看做+1,如何判断序列合法和不合法的方法是: 

1.序列从左加到右,中间的和如果出现大于0的情况。比如这个序列"(()))(",当我加到第五个字符的时候,它小于0了,所以是非法的。2.如果序列加完之后,和不为0,说明括号数目没有匹配起来,也是非法序列。

class Solution {private:vector<string> result;public:void rec(int maxDepth, int depth, int subSum, string str, char par) {(par == '(') ? subSum += -1 : subSum += 1;if (depth == maxDepth) {if (subSum == 0)result.push_back(str);return;} else if (subSum > 0)return;rec(maxDepth, depth + 1, subSum, str + '(', '(');rec(maxDepth, depth + 1, subSum, str + ')', ')');}vector<string> generateParenthesis(int n) {result.clear();if (n == 0)                return result;rec(n * 2, 1, 0, "(", '(');return result;}};


0 0
原创粉丝点击