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

Generate Parentheses

时间:2015-10-13 00:14:12      阅读:209      评论: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:

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

 

Runtime: 4ms

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> result;
 5         if(n <= 0) return result;
 6         
 7         helper(result, "", n, n);
 8         return result;
 9     }
10     void helper(vector<string>& result, string temp, int left, int right){
11         if(left > right) return;
12         
13         if(left == 0 && right == 0){
14             result.push_back(temp);
15             return;
16         }
17         
18         if(left > 0)
19             helper(result, temp + "(", left - 1, right);
20         
21         if(right > 0)
22             helper(result, temp + ")", left, right - 1);
23         
24     }
25 };

 

Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4873282.html

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