码迷,mamicode.com
首页 > 其他好文 > 详细

Generate Parentheses - LeetCode

时间:2015-10-30 07:06:46      阅读:174      评论: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:

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

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

递归过程中,我们使用两个变量,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 };

 

Generate Parentheses - LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/4922292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!