首页 > 其他 > 详细

Generate Parentheses

时间:2015-10-13 00:13:47      阅读:251      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!