Generate Parentheses - LeetCode

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:

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

思路:我们通过递归来生成所有结果。

递归过程中,我们使用两个变量,left_left和right_left,分别表示当前左括号还要出现多少次以及右括号还要出现多少次。

这里有两种情况要注意:当left_left = right_left时,当前位置应该至少插入1个左括号,不然就不合法了。

当left_left < right_left时,说明前面左括号比右括号要多,这里可以不插入左括号。

 1 class Solution {
 2 public:
 3     void genString(vector<string>& res, int left_left, int right_left, string cur)
 4     {
 5         if (!left_left && !right_left)
 6             res.push_back(cur);
 7         else
 8         {
 9             if (left_left < right_left)
10                 genString(res, left_left, right_left - 1, cur + ")");
11             for (int i = 1; i <= left_left; i++)
12             {
13                 cur.append("(");
14                 genString(res, left_left - i, right_left - 1, cur + ")");
15             }
16         }
17     }
18     vector<string> generateParenthesis(int n) {
19         vector<string> res;
20         genString(res, n, n, "");
21         return res;
22     }
23 };

 

posted @ 2015-10-30 06:36  fenshen371  阅读(135)  评论(0编辑  收藏  举报